DOM4J生成和解析XML文档
3.DOM4J生成和解析XML文档
DOM4J 是一个非常非常优秀的Java XML
API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。如今你可以看到越来越多的 Java 软件都在使用 DOM4J 来读写
XML,特别值得一提的是连 Sun 的 JAXM 也在用 DOM4J。
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
*
* @author hongliang.dinghl
* Dom4j 生成XML文档与解析XML文档
*/
public class Dom4jDemo implements XmlDocument {
public void createXml(String fileName) {
Document document = DocumentHelper.createDocument();
Element employees=document.addElement("employees");
Element employee=employees.addElement("employee");
Element name= employee.addElement("name");
name.setText("ddvip");
Element sex=employee.addElement("sex");
sex.setText("m");
Element age=employee.addElement("age");
age.setText("29");
try {
Writer fileWriter=new FileWriter(fileName);
XMLWriter xmlWriter=new XMLWriter(fileWriter);
xmlWriter.write(document);
xmlWriter.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void parserXml(String fileName) {
File inputXml=new File(fileName);
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(inputXml);
Element employees=document.getRootElement();
for(Iterator i = employees.elementIterator(); i.hasNext();){
Element employee = (Element) i.next();
for(Iterator j = employee.elementIterator(); j.hasNext();){
Element node=(Element) j.next();
System.out.println(node.getName()+":"+node.getText());
}
}
} catch (DocumentException e) {
System.out.println(e.getMessage());
}
System.out.println("dom4j parserXml");
}
}