【发布时间】:2015-03-16 09:30:30
【问题描述】:
<?xml version="1.0" encoding="UTF-8"?>
<invoice>
<obs>
<ob>
<code>ABC</code>
</ob>
<ob>
<code>123</code>
</ob>
</obs>
</invoice>
<invoice>
<obs>
<ob>
<code>DEF</code>
</ob>
</obs>
</invoice>
</invoices>
问题:
我有那个 xml,它将从外部系统传给我,它可以有大量的 invoice 节点,一个 invoice 节点可以有大量的“代码”节点。我想读取所有“发票”节点的code 节点并将它们保存在这样的数组中:
invoice[1].code[1]=ABC
invoice[1].code[2]=123
invoice[2].code[1]=DEF
如何在 JAVA 中使用 XPathExpression 做到这一点。我的代码在下面,它不起作用。
expr = xpath.compile("//invoices/invoice/obs/ob/code/text()");
result1=expr.evaluate(dc, XPathConstants.NODESET);
nodes =(NodeList)result1;
如果节点数量多,请给出一些通用解决方案。
【问题讨论】:
-
xpath 通过的节点有 2 个,如果只需要一个节点,可以从节点获取。
nodes.item(0); -
请再看一遍问题,我做了一些修改