dom4j的基本操作
/** * 建立一个XML文档,文档名由输入属性决定 * @param filename 需建立的文件名 * @return 返回操作结果, 0表失败, 1表成功 */ import java.io.File; import java.io.FileWriter; import org.dom4j.io.XMLWriter; import org.dom4j.*; public class CreateDoc{ public int createXMLFile(String filename){ /** 返回操作结果, 0表失败, 1表成功 */ int returnValue = 0; /** 建立document对象 */ Document document =DocumentHelper.createDocument(); /** 建立XML文档的根books */ Element booksElement = document.addElement("books"); /** 加入一行注释 */ booksElement.addComment("This is a test for dom4j, holen, 2004.9.11"); /** 加入第一个book节点 */ Element bookElement = booksElement.addElement("book"); /** 加入show属性内容 */ bookElement.addAttribute("show","yes"); /** 加入title节点 */ Element titleElement = bookElement.addElement("title"); /** 为title设置内容 */ titleElement.setText("Dom4j Tutorials"); /** 类似的完成后两个book */ bookElement = booksElement.addElement("book"); bookElement.addAttribute("show","yes"); titleElement = bookElement.addElement("title"); titleElement.setText("Lucene Studing"); bookElement = booksElement.addElement("book"); bookElement.addAttribute("show","no"); titleElement = bookElement.addElement("title"); titleElement.setText("Lucene in Action"); /** 加入owner节点 */ Element ownerElement = booksElement.addElement("owner"); ownerElement.setText("O'Reilly"); try{ /** 将document中的内容写入文件中 */ XMLWriter writer = new XMLWriter(new FileWriter(new File(filename))); writer.write(document); writer.close(); /** 执行成功,需返回1 */ returnValue = 1; }catch(Exception ex){ ex.printStackTrace(); } return returnValue; } public static void main(String[]args){ CreateDoc cd=new CreateDoc(); int i=cd.createXMLFile("D:\\mybook.xml"); if(i==1){ System.out.println("建立成功!"); } else{ System.out.println("建立失败!"); } } } =================================================================== dom4j写xml文件测试: package com.yanek.demo.xml.test; import java.io.File; import java.io.FileWriter; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.XMLWriter; public class DOM4j { public static void main(String[] args) { // dom4j解析xml测试 // 1. dom4j写xml /* * <?xml version="1.0" encoding="UTF-8"?> <actions> <action path="/test" * class="com.mystruts.demo.LoginAction"> <forward name="success" * url="hello.jsp"/> <forward name="fail" url="fail.jsp"/> </action> * <action path="/user" class="com.mystruts.demo.UserAction"> <forward * name="success" url="list.jsp"/> <forward name="fail" url="fail.jsp"/> * </action> </actions> */ Document document = DocumentHelper.createDocument(); Element actionsElement = document.addElement("actions"); Element actionElement1 = actionsElement.addElement("action"); actionElement1.addAttribute("path", "/test"); actionElement1.addAttribute("class", "com.mystruts.demo.LoginAction"); Element forwardElement1 = actionElement1.addElement("forward"); forwardElement1.addAttribute("name", "success"); forwardElement1.addAttribute("url", "hello.jsp"); Element forwardElement2 = actionElement1.addElement("forward"); forwardElement2.addAttribute("name", "fail"); forwardElement2.addAttribute("url", "fail.jsp"); Element actionElement2 = actionsElement.addElement("action"); actionElement2.addAttribute("path", "/user"); actionElement2.addAttribute("class", "com.mystruts.demo.UserAction"); Element forwardElement21 = actionElement2.addElement("forward"); forwardElement21.addAttribute("name", "success"); forwardElement21.addAttribute("url", "list.jsp"); Element forwardElement22 = actionElement2.addElement("forward"); forwardElement22.addAttribute("name", "fail"); forwardElement22.addAttribute("url", "fail.jsp"); try { /** 将document中的内容写入文件中 */ XMLWriter writer = new XMLWriter(new FileWriter(new File( "d:\\mystruts.xml"))); writer.write(document); writer.close(); /** 执行成功,需返回1 */ } catch (Exception ex) { ex.printStackTrace(); } System.out.println(document.asXML()); } } 生成xml: <?xml version="1.0" encoding="UTF-8"?> <actions><action path="/test" class="com.mystruts.demo.LoginAction"><forward name="success" url="hello.jsp"/><forward name="fail" url="fail.jsp"/></action><action path="/user" class="com.mystruts.demo.UserAction"><forward name="success" url="list.jsp"/><forward name="fail" url="fail.jsp"/></action></actions> 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/5iasp/archive/2009/06/12/4263354.aspx ======================================================================================= import java.io.File; import java.io.FileWriter; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class DOM4JTest { * DOM4J读写XML示例 * * @param args * @throws Exception */ public static void main(String[] args) { try { XMLWriter writer = null ; // 声明写XML的对象 SAXReader reader = new SAXReader(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding( " GBK " ); // 设置XML文件的编码格式 String filePath = " d:\\student.xml " ; File file = new File(filePath); if (file.exists()) { Document document = reader.read(file); // 读取XML文件 Element root = document.getRootElement(); // 得到根节点 boolean bl = false ; for (Iterator i = root.elementIterator( " 学生 " ); i.hasNext();) { Element student = (Element) i.next(); if (student.attributeValue( " sid " ).equals( " 001 " )) { // 修改学生sid=001的学生信息 student.selectSingleNode( " 姓名 " ).setText( " 王五 " ); student.selectSingleNode( " 年龄 " ).setText( " 25 " ); writer = new XMLWriter( new FileWriter(filePath), format); writer.write(document); writer.close(); bl = true ; break ; } } if (bl) { // 添加一个学生信息 Element student = root.addElement( " 学生 " ); student.addAttribute( " sid " , " 100 " ); Element sid = student.addElement( " 编号 " ); sid.setText( " 100 " ); Element name = student.addElement( " 姓名 " ); name.setText( " 嘎嘎 " ); Element sex = student.addElement( " 性别 " ); sex.setText( " 男 " ); Element age = student.addElement( " 年龄 " ); age.setText( " 21 " ); writer = new XMLWriter( new FileWriter(filePath), format); writer.write(document); writer.close(); } } else { // 新建student.xml文件并新增内容 Document _document = DocumentHelper.createDocument(); Element _root = _document.addElement( " 学生信息 " ); Element _student = _root.addElement( " 学生 " ); _student.addAttribute( " sid " , " 001 " ); Element _id = _student.addElement( " 编号 " ); _id.setText( " 001 " ); Element _name = _student.addElement( " 姓名 " ); _name.setText( " 灰机 " ); Element _age = _student.addElement( " 年龄 " ); _age.setText( " 18 " ); writer = new XMLWriter( new FileWriter(file), format); writer.write(_document); writer.close(); } System.out.println( " 操作结束! " ); } catch (Exception e) { e.printStackTrace(); } } } 执行结果应该是这样: 循环解析节点: private void getAllNodes(String xml) { try { Document authtmp = DocumentHelper.parseText(xml); List < Element > list = authtmp.selectNodes( " //sms/node " ); for ( int j = 0 ; j < list.size(); j ++ ) { Element node = (Element) list.get(j); nodeByNodes(node); } } catch (Exception e) { e.printStackTrace(); } } private void nodeByNodes(Element node) { if (node.element( " node " ) != null ) { String id = node.attributeValue( " id " ); String name = node.attributeValue( " name " ); System.out.print(id + " ------- " ); System.out.println(name); for (Iterator i = node.elementIterator( " node " ); i.hasNext();) { Element newNode = (Element) i.next(); nodeByNodes(newNode); } } else { String id = node.attributeValue( " id " ); String name = node.attributeValue( " name " ); System.out.print(id + " ------- " ); System.out.println(name); } } 其次DOM4J的解释 一.Document对象相关 1.读取XML文件,获得document对象. SAXReader reader = new SAXReader(); Document document = reader.read( new File( " input.xml " )); 2.解析XML形式的文本,得到document对象. String text = " <members></members> "; Document document = DocumentHelper.parseText(text); 3.主动创建document对象. Document document = DocumentHelper.createDocument(); Element root = document.addElement( " members " ); // 创建根节点 二.节点相关 1.获取文档的根节点. Element rootElm = document.getRootElement(); 2.取得某节点的单个子节点. Element memberElm = root.element( " member " ); // "member"是节点名 3.取得节点的文字 String text = memberElm.getText(); 也可以用: String text = root.elementText( " name " ); 这个是取得根节点下的name字节点的文字. 4.取得某节点下名为"member"的所有字节点并进行遍历. List nodes = rootElm.elements( " member "); for (Iterator it = nodes.iterator(); it.hasNext();) { Element elm = (Element) it.next(); // do something } 5.对某节点下的所有子节点进行遍历. for (Iterator it = root.elementIterator();it.hasNext();) { Element element = (Element) it.next(); // do something } 6.在某节点下添加子节点. Element ageElm = newMemberElm.addElement( " age " ); 7.设置节点文字. ageElm.setText( " 29 " ); 8.删除某节点. parentElm.remove(childElm); // childElm是待删除的节点,parentElm是其父节点 9.添加一个CDATA节点. Element contentElm = infoElm.addElement( " content " ); contentElm.addCDATA(diary.getContent()); contentElm.getText(); // 特别说明:获取节点的CDATA值与获取节点的值是一个方法 contentElm.clearContent(); //清除节点中的内容,CDATA亦可 三.属性相关. 1.取得某节点下的某属性 Element root = document.getRootElement(); Attribute attribute = root.attribute( " size " ); // 属性名name 2.取得属性的文字 String text = attribute.getText(); 也可以用: String text2 = root.element( " name " ).attributeValue( " firstname " ); 这个是取得根节点下name字节点的属性firstname的值. 3.遍历某节点的所有属性 Element root = document.getRootElement(); for (Iterator it = root.attributeIterator();it.hasNext();) { Attribute attribute = (Attribute) it.next(); String text = attribute.getText(); System.out.println(text); } 4.设置某节点的属性和文字. newMemberElm.addAttribute( " name " , " sitinspring " ); 5.设置属性的文字 Attribute attribute = root.attribute( " name " ); attribute.setText( " sitinspring " ); 6.删除某属性 Attribute attribute = root.attribute( " size " ); // 属性名name root.remove(attribute); 四.将文档写入XML文件. 1.文档中全为英文,不设置编码,直接写入的形式. XMLWriter writer = new XMLWriter( new FileWriter( " output.xml " ));