如何使用dom4j解析多节点的xml文件呢?求助!如以下例子
答案:1 悬赏:70 手机版
解决时间 2021-02-21 21:15
- 提问者网友:富士山上尢
- 2021-02-21 09:37
2 测试 2 测试
最佳答案
- 五星知识达人网友:白昼之月
- 2021-02-21 10:36
按照你的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更换下,结构清晰,解析简单
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯