dom4j,常用的两种方式,

 父标签下,多个子标签,获取子标签的值

例如
<?xml version="1.0" encoding="UTF-8"?>
<TKECI>
<MESSAGE>

<RESULT>Y</RESULT>
<RESULTDESC>成功!</RESULTDESC>
<PRICECODE>544</PRICECODE>
<PRICECODEDESC>结账</PRICECODEDESC>
<PRICElIST>
<PRICENODE>
<PRICETIME>20120</PRICETIME>
<PRICE>081</PRICE>
</PRICENODE >
<PRICENODE>
<PRICETIME>20120130</PRICETIME>
<PRICE>1.3531</PRICE>
</PRICENODE >
<!-- 多个PRICENODE节点 -->
</PRICElIST>
</MESSAGE>
</TKECI>
 
 
SAXReader reader = new SAXReader();
Document document;
document = reader.read(可写一个XML的路径/如果是字符串 new StringReader(""));
 
//循环得到多个子标签的值
Element rootElement = document.getRootElement();//得到父节点
 
//根据父节点,得到子节点,(必须一级一级的拿)
List elements = rootElement.element("MESSAGE").element("PRICElIST").elements();
Iterator it = elements.iterator();
//拿到所有相同的子标签后循环
while(it.hasNext()) {
baseEntity = new QueriesOneBaseEntity();
Element elementList = (Element) it.next();
String a = elementList.element("PRICE").getTextTrim());
String b = elementList.element("PRICETIME").getTextTrim());
syso(a + b);
}
 
//如果不用循环拿到所有相同子标签的值得话,可直接拿,
Node node = document.selectSingleNode("/TKECI/MESSAGE/RESULTDESC");
if(node != null) {
String a = node.getText().trim();
syso(a);
}
 
dom4j还有很多方法,这里这写了本人常用的两种

你可能感兴趣的:(dom4j)