偶没用xpath来写,改天也去学习下xpath
<?xml version="1.0" encoding="GBK"?>
<Records Version="0.1">
<Record busiId="0807291252000000100001" companyId="001">
<CustomerId>axiu45555 </CustomerId>
<Content>
<Goods>
<Name>西湖牛肉羹 </Name>
</Goods>
<Goods>
<Name>鱼香肉丝 </Name>
</Goods>
</Content>
</Record>
<Record busiId="0807291252000000100002" companyId="002">
<CustomerId>geng888 </CustomerId>>
<Content>
<Goods>
<Name>剁椒鱼头 </Name>
</Goods>
</Content>
</Record>
<Record busiId="0807291252000000100003" companyId="003">
<CustomerId>xfsss </CustomerId>>
<Content>
<Goods>
<Name>麻婆豆腐 </Name>
</Goods>
<Goods>
<Name>酸菜鱼</Name>
</Goods>
<Goods>
<Name>宫保鸡丁 </Name>
</Goods>
</Content>
</Record>
</Records> import java.io.File;
import java.util.Iterator;
import java.util.List;import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;public class Test { public static void doSomething() throws DocumentException {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File("C:/a.xml"));
Element rootElement = document.getRootElement();
System.out.println(rootElement.getName());
List<Element> listRecord = rootElement.elements("Record");
Iterator<Element> itRecord = listRecord.iterator();
while(itRecord.hasNext()){
Element e = itRecord.next();
System.out.println(e.attributeValue("busiId") + "=" + e.attributeValue("companyId"));
List<Element> listGoods = e.element("Content").elements("Goods");
Iterator<Element> itGoods = listGoods.iterator();
while(itGoods.hasNext()){
Element e2 = itGoods.next().element("Name");
System.out.println(e2.getName() + "=" + e2.getTextTrim());
}
}
} public static void main(String[] args) {
try {
doSomething();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
0807291252000000100001=001
Name=西湖牛肉羹
Name=鱼香肉丝
0807291252000000100002=002
Name=剁椒鱼头
0807291252000000100003=003
Name=麻婆豆腐
Name=酸菜鱼
Name=宫保鸡丁