Number 节点列表与 xpath 错误 java

Number node list is wrong with xpath java

我有一个这样的 xml 文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<fields>
    <field>
        <name>ID</name>
        <shortcode>id</shortcode>
        <display>true</display>
        <table_id>1</table_id>
    </field>
    <field>
        <name>Name</name>
        <shortcode>name</shortcode>
        <display>true</display>
        <table_id>1</table_id>
    </field>
    <field>
        <name>ID</name>
        <shortcode>id</shortcode>
        <display>true</display>
        <table_id>2</table_id>
    </field>
    <field>
        <name>Name</name>
        <shortcode>name</shortcode>
        <display>true</display>
        <table_id>2</table_id>
    </field>
    <field>
        <name>ID</name>
        <shortcode>id</shortcode>
        <display>true</display>
        <table_id>3</table_id>
    </field>
    <field>
        <name>Name</name>
        <shortcode>name</shortcode>
        <display>true</display>
        <table_id>3</table_id>
    </field>
</fields>

我想获取所有 table_id=1(或 2、3、..)的 "field" 元素。我尝试了下面的代码,但它是错误的:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forgot this
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(filePath);

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("fields/field[table_id=1]");

Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;

for (int i = 0; i < nodes.getLength(); i++) {
    //System.out.println(nodes.item(i).getChildNodes().item(i).getTextContent());
    NodeList childNodes = nodes.item(i).getChildNodes();
    for (int j = 0; j < childNodes.getLength(); j++) {
        System.out.println(childNodes.item(j).getTextContent());
    }
    System.out.println(childNodes.getLength()); // **why 9 nodes**
}

不知道为什么是9?我想要的结果是 4 个节点。请帮助我!

子节点 nodes 包含文本节点 - 元素

<field>
    <name>ID</name>
    <shortcode>id</shortcode>
    <display>true</display>
    <table_id>1</table_id>
</field>

确实有九个子节点,由四个子元素节点加上<field><name></table_id></field>之间的五个空白文本节点组成, 以及一个子元素的结束标记和下一个子元素的开始标记之间。

如果您只关心子 元素 而不是子 节点 那么您应该只过滤那些 instanceof Element,或者您可以使用另一个 XPath 表达式

仅提取元素
XPathExpression childEltsExpr = xpath.compile("*");

然后在 for 循环中

NodeList childElements = (NodeList)childEltsExpr.evaluate(nodes.item(i),
      XPathConstants.NODESET);

因为你还有文本节点(标签之间的空格)。您应该尝试 select 只有作为元素节点的子节点。例如 node.getNodeType()