可用于读取和写入 XML 的 XML 的基本 Java API 是DOM
StaX
. 然而 DOM4J 可以更好,因为它有更简单的 API。
这是创建 XML 文档的简单方法
public void createXML() throws IOException {
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement("Students");
Element studentElement = rootElement.addElement("student").addAttribute("country", "USA");
studentElement.addElement("id").addText("1");
studentElement.addElement("name").addText("Peter");
XMLWriter writer = new XMLWriter(new FileWriter("Students.xml"));
//Note that You can format this XML document
/*
* FileWriter output = new FileWriter(new File("Students.xml"));
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(output,format);<- will fomat the output
*/
//You can print this to the console and see what it looks like
String xmlElement = document.asXML();
System.out.println(xmlElement);
writer.write(document);
writer.close();
}
并阅读 student.xml
public void readXML() throws SAXException, IOException,
ParserConfigurationException, DocumentException {
/*Integration with DOM
DOMReader reader = new DOMReader();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = reader.read(builder.parse(new File("Students.xml")));
*/
SAXReader readerSAX = new SAXReader();
Document document2 = readerSAX.read(new File("Students.xml"));
Element root = document2.getRootElement();
Student student = null;
List<Student> studentsList = new ArrayList<Student>();
if (root.getName().equalsIgnoreCase("students")) {
for (@SuppressWarnings("unchecked")
Iterator<Student> i = root.elementIterator(); i.hasNext();) {
Element element = (Element) i.next();
if ("student".equalsIgnoreCase(element.getName())) {
student = new Student();
for (int j = 0, size = element.nodeCount(); j < size; j++) {
Node node = (Node) element.node(j);
if (node instanceof Element) {
if ("id".equalsIgnoreCase(node.getName())) {
student.setId(Integer.parseInt(node.getText()));
} else if ("name".equalsIgnoreCase(node.getName())) {
student.setName(node.getText());
}
}
}
studentsList.add(student);
}
}
}
for(Student stud : studentsList){
System.out.println(stud);
}
}