DOM4J官方网站: http://www.dom4j.org/
dom4j是一个Java的XML API,类似于jdom,用来读写XML文件的。dom4j是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件,可以在SourceForge上找到它。在IBM developerWorks上面可以找到一篇文章,对主流的Java XML API进行的性能、功能和易用性的评测,dom4j无论在哪个方面都是非常出色的。如今你可以看到越来越多的Java软件都在使用dom4j来读写XML,特别值得一提的是连Sun的JAXM也在用dom4j。这是必须使用的jar包,Hibernate用它来读写配置文件。
1.1 XML使用DOM4J方式生成XML文件
引入dom4j 新建Folder,导入dom4j所用的jar包,右键 --> Build Path --> Add To Build Path dom4j-1.6.1.jar
package com.andrew.xml; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class DOM4J01 { public static void main(String[] args) { Document document = DocumentHelper.createDocument(); Element studentElement = document.addElement("student"); studentElement.addAttribute("id", "001"); studentElement.addAttribute("aa", "xx"); Element name = studentElement.addElement("name"); name.setText("张三"); Element sex = studentElement.addElement("sex"); sex.setText("男"); Element age = studentElement.addElement("age"); age.setText("20"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); try { XMLWriter writer = new XMLWriter(new FileOutputStream("src/studentDOM4JOut.xml"), format); writer.write(document); writer.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 运行结果: 在src在生成studentDOM4JOut.xml张三 男 20
1.2 XML使用DOM4J方式读取XML文件
张三 男 20 李四 女 21
package com.andrew.xml; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class DOM4J02 { public static void main(String[] args) throws Exception { SAXReader saxReader = new SAXReader(); Document document = saxReader.read("src/studentsSax.xml"); Element rootElement = document.getRootElement(); Iterator iter = rootElement.elementIterator(); while (iter.hasNext()) { Element studentElement = (Element) iter.next(); System.out.println("学号:" + studentElement.attributeValue("id")); System.out.println("姓名:" + studentElement.elementText("name")); System.out.println("性别:" + studentElement.elementText("sex")); System.out.println("年龄:" + studentElement.elementText("age")); System.out.println("========="); } } } 运行结果: 学号:001 姓名:张三 性别:男 年龄:20 ========= 学号:002 姓名:李四 性别:女 年龄:21 =========