给定以下 XML 文档:
<?xml version="1.0" encoding="UTF-8"?>
<InlinePurchaseOrder>
<largeMessage>
<BuyersID>20031234-1</BuyersID>
<IssueDate>2003-01-23</IssueDate>
<LineExtensionTotalAmount amountCurrencyID="USD" amountCurrencyCodeListVersionID="0.3">438.50</LineExtensionTotalAmount>
<BuyerParty>
<Party>
<PartyName>
<Name>Bills Microdevices</Name>
<Name>BM</Name>
<Name>BMic</Name>
</PartyName>
</Party>
</BuyerParty>
</largeMessage>
</InlinePurchaseOrder>
我发出一个 XPath 来导航到<PartyName>
节点,然后我想发出第二个 XPath 来获取所有<Name>
节点,并记录它们的位置。
出于某种原因,NodeRecorder.iterate()
即使节点被正确记录,我也立即返回 -1,我调用了resetPointer()
,并且我正在向前移动。我有其他具有这种逻辑(但不同的 XPath)的文档有效,但这个不是。有任何想法吗?
演示代码:
File f = new File("noderecorder.xml");
FileInputStream fis = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
fis.read(b);
fis.close();
VTDGen vg = new VTDGen();
vg.setDoc(b);
vg.parse(false);
VTDNav vn = vg.getNav();
AutoPilot partyNameXPath = new AutoPilot(vn);
partyNameXPath.selectXPath("largeMessage/BuyerParty/Party/PartyName");
// Find PartyName
while (partyNameXPath.evalXPath() != -1) {
System.out.println("Found: " + vn.getCurrentIndex() + " " +
vn.toRawString(vn.getCurrentIndex()));
NodeRecorder nr = new NodeRecorder(vn);
// Find all Names and record their positions
AutoPilot nameXPath = new AutoPilot(vn);
nameXPath.selectXPath("Name");
while (nameXPath.evalXPath() != -1) {
System.out.println("Found: " + vn.getCurrentIndex() + " " +
vn.toRawString(vn.getCurrentIndex()));
nr.record();
}
nr.resetPointer();
System.out.println("Index before nr.iterate: " + vn.getCurrentIndex());
// Do some other work...
// Now go and iterate over the nodes we recorded
while (nr.iterate() != -1) {
System.out.println("Re-found: " + vn.getCurrentIndex() + " " +
vn.toRawString(vn.getCurrentIndex()));
}
System.out.println("Index after nr.iterate: " +
vn.getCurrentIndex());
}
输出:
Found: 19 PartyName
Found: 20 Name
Found: 22 Name
Found: 24 Name
Index before nr.iterate: 19
Index after nr.iterate: -1
编辑:刚刚尝试了一个嵌套较少的修改文档,并且这个有效(将partyNameXPath更改为“PartyName”),问题似乎与深度相关:
<?xml version="1.0" encoding="UTF-8"?>
<InlinePurchaseOrder>
<PartyName>
<Name>Bills Microdevices</Name>
<Name>BM</Name>
<Name>BMic</Name>
</PartyName>
</InlinePurchaseOrder>
输出:
Found: 6 PartyName
Found: 7 Name
Found: 9 Name
Found: 11 Name
Index before nr.iterate: 6
Re-found: 7 Name
Re-found: 9 Name
Re-found: 11 Name
Index after nr.iterate: 11