1. 用Java代码生成xml文档
package com.test.dom;import java.io.FileOutputStream;import java.io.IOException;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.XMLWriter;public class Dom4jDemo { public static void main(String[] args) throws IOException { Document doc = DocumentHelper.createDocument(); Element root = DocumentHelper.createElement("books"); doc.setRootElement(root); root.addAttribute("id", "001"); Element bookElement = root.addElement("book"); Element titleElement = bookElement.addElement("title"); titleElement.setText("Harry Potter"); Element authorElement = bookElement.addElement("author"); authorElement.setText("J K. Rowling"); // 输出到控制台中 XMLWriter xmlWriter = new XMLWriter(); xmlWriter.write(doc); // 把生成的xml文档存放在硬盘上 true代表是否换行 OutputFormat format = new OutputFormat(" ", true); format.setEncoding("GBK");// 设置编码格式 XMLWriter fileXmlWriter = new XMLWriter(new FileOutputStream("e:/books.xml"), format); fileXmlWriter.write(doc); fileXmlWriter.close(); }}
xml结构
Harry Potter J K. Rowling
2. 解析xml
从String中获取
String xmlStr = "...... "; Document document = DocumentHelper.parseText(xmlStr);
从文件中获取
//创建SAXReader对象 SAXReader reader = new SAXReader(); //读取文件 转换成Document Document document = reader.read(new File("books.xml"));