DOM4J
DOM4J生成和解析XML文档DOM4J 是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。如今你可以看到越来越多的 Java 软件都在使用 DOM4J 来读写 XML,特别值得一提的是连 Sun 的 JAXM 也在用 DOM4J。
/**
* 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("桥本有菜"); Element sex = employee.addElement("sex"); sex.setText("女"); Element age = employee.addElement("age"); age.setText("24"); 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.