Dom4j是一个易用的、开源的库,用于XML,XPath和XSLT。它应用于Java平台,采用了Java集合框架并完全支持DOM,SAX和JAXP。
做为解析xml文件 比较好的方式,目前被广泛应用,不多说了,有个简单例子,供参考:
package com.dom.utils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* * @description 解析xml字符串
* * @author liguohu09@gmail.com
* * @Date 2012-02-09
*/
public class Test {
public void readStringXml(String xml) {
Document doc = null;
try { // 读取并解析XML文档
// SAXReader就是一个管道,用一个流的方式,把xml文件读出来 // //
SAXReader reader = new SAXReader(); // User.hbm.xml表示你要解析的xml文档 //
// Document document = reader.read(new File("User.hbm.xml")); // 下面的是通过解析xml字符串的
Document document = reader.read(new File("error all.xml")); // 下面的是通过解析xml字符串的
doc = DocumentHelper.parseText(xml); // 将字符串转为XML
Element rootElt = doc.getRootElement(); // 获取根节点
System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称
Iterator iter = rootElt.elementIterator("head"); // 获取根节点下的子节点head
// 遍历head节点
while (iter.hasNext()) {
Element recordEle = (Element) iter.next();
String title = recordEle.elementTextTrim("title"); // 拿到head节点下的子节点title值
System.out.println("title:" + title);
Iterator iters = recordEle.elementIterator("script"); // 获取子节点head下的子节点script
// 遍历Header节点下的Response节点
while (iters.hasNext()) {
Element itemEle = (Element) iters.next();
String username = itemEle.elementTextTrim("username"); // 拿到head下的子节点script下的字节点username的值
String password = itemEle.elementTextTrim("password");
System.out.println("username:" + username);
System.out.println("password:" + password);
}
}
Iterator iterss = rootElt.elementIterator("body"); // /获取根节点下的子节点body
// // 遍历body节点
while (iterss.hasNext()) {
Element recordEless = (Element) iterss.next();
String result = recordEless.elementTextTrim("result"); // 拿到body节点下的子节点result值
System.out.println("result:" + result);
Iterator itersElIterator = recordEless.elementIterator("form"); // 获取子节点body下的子节点form
// 遍历Header节点下的Response节点
while (itersElIterator.hasNext()) {
Element itemEle = (Element) itersElIterator.next();
String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子节点form下的字节点banlce的值
String subID = itemEle.elementTextTrim("subID");
System.out.println("banlce:" + banlce);
System.out.println("subID:" + subID);
}
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* * @description 将xml字符串转换成map
* @param xml
* @return Map
*/
public static List readStringXmlOut(String xml) {
// Map map = new HashMap();
List errorAll = null;
Document doc = null;
try {
doc = DocumentHelper.parseText(xml); // 将字符串转为XML
Element rootElt = doc.getRootElement(); // 获取根节点
System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称
Iterator iter = rootElt.elementIterator("UniverseInterfaceResult"); // 获取根节点下的子节点UniverseInterfaceResult
// // 遍历string节点
while (iter.hasNext()) {
Element recordEle = (Element) iter.next();
String message = recordEle.elementTextTrim("Message"); // 拿到UniverseInterfaceResult节点下的子节点Message值
System.out.println("message:" + message);
//返回值是success,则不做处理;否则,取所有报错订单信息.
if("Failed".equals(message)){
//初始化list.
errorAll = new ArrayList();
Element detailsEle = recordEle.element("Details");// 拿到UniverseInterfaceResult节点下的子节点Details值
Iterator iters = detailsEle.elementIterator("ErrorDetail");
// 遍历ErrorDetail节点下的Response节点.
while (iters.hasNext()) {
Element itemEle = (Element) iters.next();
System.out.println("ID:" + itemEle.elementText("Id"));
System.out.println("Detail:" + itemEle.elementText("Detail"));
Map errorMsg = new HashMap();
errorMsg.put("Id", itemEle.elementText("Id")); // 拿到每个Details下的子节点ErrorDetail下的字节点Id的值
errorMsg.put("Detail", itemEle.elementText("Detail"));
errorAll.add(errorMsg);
}
}
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return errorAll;
}
public static void main(String[] args) { // 下面是需要解析的xml字符串例子
/**
String xmlString = "<string xmlns='http://SGMPortal.Universe.QIP/'>"
+"<universeinterfaceresult xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>"
+"<details></details>"
+"<message>Success</message>"
+"<totallyfailed>false</totallyfailed>"
+"</universeinterfaceresult>" + "</string>";
*/
String xmlString = ""
+"<string xmlns='http://SGMPortal.Universe.QIP/'>"
+"<universeinterfaceresult xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>"
+"<details>"
+"<errordetail>"
+"<id>13A3669B705C2F614825797C0043790F</id>"
+"<detailmessage>Error occurred while parsing audit log with Id 13A3669B705C2F614825797C0043790F</detailmessage>"
+"<detail>System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 20."
+"at System.DateTime.Parse(String s)"
+"</detail>"
+"</errordetail>"
+"<errordetail>"
+"<id>14F86BD2E7C9C2DE4825797C0043784D</id>"
+"<detailmessage>Error occurred while parsing audit log with Id 14F86BD2E7C9C2DE4825797C0043784D</detailmessage>"
+"<detail>System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 20."
+"at System.DateTime.Parse(String s)"
+"</errordetail>"
+"<errordetail>"
+"<id>FAAB4D7FD87B79DB4825797C0042849D</id>"
+"<detailmessage>Error occurred while parsing audit log with Id FAAB4D7FD87B79DB4825797C0042849D</detailmessage>"
+"<detail>System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 20."
+"at System.DateTime.Parse(String s)"
+"</errordetail>"
+"<errordetail>"
+"<id>FA24B28DF49BF4634825797C00428263</id>"
+"<detailmessage>Error occurred while parsing audit log with Id FA24B28DF49BF4634825797C00428263</detailmessage>"
+"<detail>System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 20."
+"at System.DateTime.Parse(String s)"
+"</errordetail>"
+"<errordetail>"
+"<id>9AE5D97B5FE83D504825797C003BB513</id>"
+"<detailmessage>Error occurred while parsing audit log with Id 9AE5D97B5FE83D504825797C003BB513</detailmessage>"
+"<detail>System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 20."
+"at System.DateTime.Parse(String s)"
+"</errordetail>"
+"<errordetail>"
+"<id>75D9D702B5D054714825797C003BB258</id>"
+"<detailmessage>Error occurred while parsing audit log with Id 75D9D702B5D054714825797C003BB258</detailmessage>"
+"<detail>System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 20."
+"at System.DateTime.Parse(String s)"
+"</errordetail>"
+"<errordetail>"
+"<id>DAFEAA6924BAD8CB4825797C003BA735</id>"
+"<detailmessage>Error occurred while parsing audit log with Id DAFEAA6924BAD8CB4825797C003BA735</detailmessage>"
+"<detail>System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 20."
+"at System.DateTime.Parse(String s)"
+"</errordetail>"
+"<errordetail>"
+"<id>6723D7ACD159BBB04825797C003BA5D1</id>"
+"<detailmessage>Error occurred while parsing audit log with Id 6723D7ACD159BBB04825797C003BA5D1</detailmessage>"
+"<detail>System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 20."
+"at System.DateTime.Parse(String s)"
+"</errordetail>"
+"<errordetail>"
+"<id>C8932D9CECFA999C4825797C003BA01D</id>"
+"<detailmessage>Error occurred while parsing audit log with Id C8932D9CECFA999C4825797C003BA01D</detailmessage>"
+"<detail>System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 20."
+"at System.DateTime.Parse(String s)"
+"</errordetail>"
+"<errordetail>"
+"<id>21289941B1E8D07B4825797C003B9AF1</id>"
+"<detailmessage>Error occurred while parsing audit log with Id 21289941B1E8D07B4825797C003B9AF1</detailmessage>"
+"<detail>System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 20."
+"at System.DateTime.Parse(String s)"
+"</errordetail>"
+"</details>"
+"<message>Failed</message>"
+"<totallyfailed>true</totallyfailed>"
+"</universeinterfaceresult>"
+"</string>";
/* * Test2 test = new Test2(); test.readStringXml(xmlString); */
List errorAll = readStringXmlOut(xmlString);
Iterator iters = errorAll.iterator();
while (iters.hasNext()) {
Map errorObj = (Map) iters.next();
System.out.println("Id{}=" + errorObj.get("Id"));
System.out.println("Detail{}=" + errorObj.get("Detail"));
}
}
}
Author: liguohu09@gmail.com
Date: 2012-02-09