gpt4 book ai didi

java - xerces Xpath - 从另一个节点搜索节点

转载 作者:行者123 更新时间:2023-12-01 14:19:23 25 4
gpt4 key购买 nike

我有以下 XML:

    <ONIXMessage>
<Product>
<RecordReference>9786071502131</RecordReference>
<RecordReference>9786071502131</RecordReference>
</Product>
<Product>
<RecordReference>9786071502131</RecordReference>
</Product>
</ONIXMessage>

下面的java代码:

    Element ONIXmessage = document.getDocumentElement();
products = XPathAPI.selectNodeList(ONIXmessage, "/ONIXMessage/Product");

for(int i = 0;i < products.getLength();i++) {
Node product = products.item(i);

NodeList prova = XPathAPI.selectNodeList(ONIXmessage, "/ONIXMessage/Product/RecordReference");
System.out.println(prova.getLength());

NodeList prova2 = XPathAPI.selectNodeList(product, "/ONIXMessage/Product/RecordReference");
System.out.println(prova2.getLength());
}

此代码返回:3 3 3 3

我认为这段代码应该返回 3 2 3 1,因为“prova”变量包含文档的所有“RecordReference”节点,而“prova2”仅包含一个产品节点的特定“RecordReference”节点。

如何使用 XPATH 只获取特定产品的节点?

最佳答案

第一个参数为 XPathAPI#selectNodeList 是 XPath 表达式的上下文。

通过product变量是合理且正确的,但是您的 XPath 查询是错误的:斜杠 /表达式开头的 表示当前上下文的根节点,在本例中为 <ONIXMessage/>元素。

相反,从点 . 表示的当前上下文开始。请记住,您的新表达式是从此上下文开始的,因此您的新 XPath 将是 ./RecordReference 。您甚至可以省略 ./ ,但我更喜欢添加这两个字符,使查询更易于阅读和理解:

NodeList prova2 = XPathAPI.selectNodeList(product, "./RecordReference");

关于java - xerces Xpath - 从另一个节点搜索节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17753095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com