gpt4 book ai didi

java - 针对子节点的 XPATH 评估

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:43 25 4
gpt4 key购买 nike

我的 xml 如下,

<students>
<Student><age>23</age><id>2000</id><name>PP2000</name></Student>
<Student><age>23</age><id>1000</id><name>PP1000</name></Student>
</students>

我有 2 个 xpath Template XPATH = students/Student 将是模板节点,但我无法对这个 xpath 进行硬编码,因为它会针对其他 XML 进行更改,并且 XML 非常动态,可以扩展(但具有相同的基本 XPATH)因此,如果我使用模板节点评估另一个 XPATH,我将使用以下代码,

XPath xpathResource = XPathFactory.newInstance().newXPath();
Document xmlDocument = //creating document;
NodeList nodeList = (NodeList)xpathResource.compile("//students/Student").evaluate(xmlDocument, XPathConstants.NODESET);
for (int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) {
Node currentNode = nodeList.item(nodeIndex);
String xpathID = "//students/Student/id";
String xpathName = "//students/Student/name";
NodeList childID = (NodeList)xpathResource.compile(xpathID).evaluate(currentNode, XPathConstants.NODESET);
NodeList childName = (NodeList)xpathResource.compile(xpathName).evaluate(currentNode, XPathConstants.NODESET);
System.out.println("node ID " +childID.item(0).getTextContent());
System.out.println("node Name " +childName.item(0).getTextContent());
}

现在的问题是,这个 for 循环将执行 2 次,但两次我都得到 2000 , PP2000 作为 ID 值。有没有办法使用针对节点的通用 XPATH 迭代到子节点。我无法针对整个 XMLDocument 使用通用 XPATH,我需要进行一些验证。我想使用 XML 节点列表作为结果集行,以便我可以验证 XML 值并完成我的工作。

最佳答案

    XPath xpathResource = XPathFactory.newInstance().newXPath();
Document xmlDocument = //creating document;
NodeList nodeList = (NodeList)xpathResource.compile("//students/Student/id").evaluate(xmlDocument, XPathConstants.NODESET);

for (int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) {
Node currentNode = nodeList.item(nodeIndex);

System.out.println("node " +currentNode.getTextContent());
}

关于java - 针对子节点的 XPATH 评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35769534/

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