import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class AnalysisUtil {
/**
* 解析XML格式的指定数据
* @param xmlString xml文件的string格式
* @param condition 需要查询的节点名称, 多个节点名称之间用","逗号隔开.
* 需要查询子节点甚至子孙节点value,可用父,子,孙的格式
* 例如"header,application"
* 如需获取节点属性值, 用.隔开
* 例如"header,application.id"
* @return
* @throws DocumentException
*/
public static String analysisXML(String xmlString, String condition)
throws DocumentException {
// 返回的字符串
String status = "";
String[] attributeList = null;
if (xmlString != null && !xmlString.equals("")) {
Document document = DocumentHelper.parseText(xmlString);
Element root = document.getRootElement();
Element reElement = root.element("Body");
String[] conditionlist = condition.split(",");
for (int i = 0; i < conditionlist.length; i++) {
if (reElement != null) {
if(conditionlist.length - 1 == i){
attributeList = conditionlist[i].toString().split("\\.");
reElement = reElement.element(attributeList[0].toString());
}else{
reElement = reElement.element(conditionlist[i].toString());
}
}
}
if (reElement != null) {
if(attributeList.length > 1){
status = reElement.attributeValue(attributeList[1].toString());
}else if(attributeList.length == 1 ){
status = reElement.getTextTrim();
}
}
}
return status;
}
public static void main (String[] egr) throws DocumentException{
//拼接地址
StringBuffer rspxmlBuff = new StringBuffer();
rspxmlBuff.append("<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\">");
rspxmlBuff.append("<env:Header/>");
rspxmlBuff.append("<env:Body>");
rspxmlBuff.append("<ns3:GetYYResponse xmlns:ns3=\"https://www.baidu.com/\">");
rspxmlBuff.append("<ProductOptionrrr id=\"39490\">");
rspxmlBuff.append("<ProductOptionuuu>");
rspxmlBuff.append("<Date>2017-05-24T00:00:00.000+10:00</Date>");
rspxmlBuff.append("<RetailPrice>76.00</RetailPrice>");
rspxmlBuff.append("<Price>76.00</Price>");
rspxmlBuff.append("<Quantity>200</Quantity>");
rspxmlBuff.append("<Status id=\"123\">AVAILABLE</Status>");
rspxmlBuff.append("<MetaData/>");
rspxmlBuff.append("</ProductOptionuuu>");
rspxmlBuff.append("</ProductOptionrrr>");
rspxmlBuff.append("</ns3:GetYYResponse>");
rspxmlBuff.append("</env:Body>");
rspxmlBuff.append("</env:Envelope>");
String Status = AnalysisUtil.analysisXML(rspxmlBuff.toString(), "GetYYResponse,ProductOptionrrr,ProductOptionuuu,Status");
String id = AnalysisUtil.analysisXML(rspxmlBuff.toString(), "GetYYResponse,ProductOptionrrr,ProductOptionuuu,Status.id");
System.out.println("Status = "+Status);
System.out.println("id = "+id);
}
}
本例引入的是 dom4j-2.0.1.jar