如何使用dom4j解析多节点的xml文件呢?求助!如以下例子
<RESULT><VALUE1id="13"><NO1>2</NO1><ADDR1>测试</ADDR1></VALUE1><VALUE2id="13"><NO2>2</N...
<RESULT>
<VALUE1 id="13">
<NO1>2</NO1>
<ADDR1>测试</ADDR1>
</VALUE1>
<VALUE2 id="13">
<NO2>2</NO2>
<ADDR2>测试</ADDR2>
</VALUE2>
</RESULT> 展开
<VALUE1 id="13">
<NO1>2</NO1>
<ADDR1>测试</ADDR1>
</VALUE1>
<VALUE2 id="13">
<NO2>2</NO2>
<ADDR2>测试</ADDR2>
</VALUE2>
</RESULT> 展开
1个回答
展开全部
按照你的xml格式。 将以上xml保存为 bb.xml
SAXReader sax = new SAXReader();
Document document= sax.read("bb.xml");
Element root = document.getRootElement();
for (Iterator iter = root.elementIterator(); iter.hasNext();) {
Element vals = (Element) iter.next();
System.out.println("name=" + vals.getName()
+ " \t attribut ID=" + vals.attributeValue("id"));
for (Iterator iterVal = vals.elementIterator(); iterVal
.hasNext();) {
Element valNode = (Element) iterVal.next();
System.out.print("\t childName=" + valNode.getName()
+ "\t childValue=" + valNode.getText());
System.out.println();
}
}
如果你把xml格式换下,保存文件 b.xml:
<RESULT>
<VALUE id="13" type="1">
<NO>2</NO>
<ADDR>测试</ADDR>
</VALUE>
<VALUE id="13" type="2">
<NO>2</NO>
<ADDR>测试</ADDR>
</VALUE>
</RESULT>
解析如下:
document = sax.read("b.xml");
root = document.getRootElement();
List ls = root.selectNodes("/RESULT/VALUE");
for (int i = 0; i < ls.size(); i++) {
Element val = (Element) ls.get(i);
Element no = val.element("NO");
Element addr = val.element("ADDR");
System.out.println("id=" + val.attributeValue("id") + "\t type="
+ val.attributeValue("type") + "\t no=" + no.getText()
+ "\t addr=" + addr.getText());
}
建议你将xml更换下,结构清晰,解析简单
SAXReader sax = new SAXReader();
Document document= sax.read("bb.xml");
Element root = document.getRootElement();
for (Iterator iter = root.elementIterator(); iter.hasNext();) {
Element vals = (Element) iter.next();
System.out.println("name=" + vals.getName()
+ " \t attribut ID=" + vals.attributeValue("id"));
for (Iterator iterVal = vals.elementIterator(); iterVal
.hasNext();) {
Element valNode = (Element) iterVal.next();
System.out.print("\t childName=" + valNode.getName()
+ "\t childValue=" + valNode.getText());
System.out.println();
}
}
如果你把xml格式换下,保存文件 b.xml:
<RESULT>
<VALUE id="13" type="1">
<NO>2</NO>
<ADDR>测试</ADDR>
</VALUE>
<VALUE id="13" type="2">
<NO>2</NO>
<ADDR>测试</ADDR>
</VALUE>
</RESULT>
解析如下:
document = sax.read("b.xml");
root = document.getRootElement();
List ls = root.selectNodes("/RESULT/VALUE");
for (int i = 0; i < ls.size(); i++) {
Element val = (Element) ls.get(i);
Element no = val.element("NO");
Element addr = val.element("ADDR");
System.out.println("id=" + val.attributeValue("id") + "\t type="
+ val.attributeValue("type") + "\t no=" + no.getText()
+ "\t addr=" + addr.getText());
}
建议你将xml更换下,结构清晰,解析简单
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询