针对子节点的 XPATH 评估



我有如下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 模板 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());
    }

最新更新