DOM4j本身还是需要使用SAX建立解析器,然后通过文档依次找到根节点,再通过根节点查找每一个节点的内容.
1.写操作
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public static void main(String[] args) {
// 1.创建文档
Document doc = DocumentHelper.createDocument();
// 2.定义节点及子节点
Element addresslist = doc.addElement("addresslist");
Element linkman = addresslist.addElement("linkman");
// 定义子节点
Element name = linkman.addElement("name");
Element email = linkman.addElement("email");
// 3.设置节点内容
name.setText("祖国");
email.setText("mxzer3200@126.com");
// 4.设置输出格式
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK"); // 设置输出编码
// 输出xml
try {
XMLWriter writer = new XMLWriter(new FileOutputStream(new File("e:"+ File.separator + "dom4j2.xml")), format);
writer.write(doc);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
生成的xml文件已格式排列的:
2.读操作
/**
* 读操作
* 使用SAX建立解析器,然后通过文档依次找到根节点,然后通过根节点找到每一个节点的内容。
*/
public static void main(String[] args) {
// 1.读取文件
File file = new File("e:" + File.separator + "dom4j2.xml");
// 2.建立SAX解析读取
SAXReader reader = new SAXReader();
// 3.读取文档
Document doc = null;
try {
doc = reader.read(file);
} catch (DocumentException e) {
e.printStackTrace();
}
// 4.获取根元素
Element root = doc.getRootElement();
// System.out.println(root.getName());
Iterator it = root.elementIterator(); // 获取全部子节点
while (it.hasNext()) {
Element linkman = (Element) it.next();
System.out.println("姓名:" + linkman.elementText("name"));
System.out.println("邮箱:" + linkman.elementText("email"));
}
}
3.解析xml方式2
<?xml version="1.0" encoding="UTF-8"?>
<Response service="ConfirmService">
<Head>ERR</Head>
<ERROR code="4001">系统发生数据错误或运行时异常</ERROR>
</Response>
String xml = "<?xml version=\'1.0\' encoding=\'UTF-8\'?><Response service=\"ConfirmService\"><Head>ERR</Head><ERROR code=\"4001\">系统发生数据错误或运行时异常</ERROR></Response>";
System.out.println(xml);
Map<String, String> map = parseXml(xml);
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
/**
* 解析XML
* @param parseXml
* @return
*/
private static Map<String, String> parseXml(String parseXml) {
Map<String, String> map = new HashMap<String, String>();
String resultHeader = "";
String errorCode = "";
String errorDetail = "";
try {
// Parse Xml
Document document = DocumentHelper.parseText(parseXml);
// Parse Header
List<Element> list = document.selectNodes("//" + "Head");
if (list != null && list.size() > 0) {
Element e = list.get(0);
List<Element> els = e.elements();
if (els.size() == 0) {
resultHeader = e.getText().trim();
}
}
// Parse Error
list = document.selectNodes("//" + "ERROR");
if (list != null && list.size() > 0) {
Element e = list.get(0);
List<Element> els = e.elements();
if (els.size() == 0) {
errorCode = e.attributeValue("code");
errorDetail = e.getTextTrim();
}
}
} catch (Exception e) {
resultHeader = "ERR";
errorCode = "9999";
errorDetail = "XML解析错误:" + e.getMessage();
}
// Set Map
map.put("header", resultHeader);
map.put("errCode", errorCode);
map.put("errDetail", errorDetail);
return map;
}