【问题标题】:Retrieve particular child node using xpath in java在java中使用xpath检索特定的子节点
【发布时间】:2021-12-23 15:32:49
【问题描述】:

我有如下的xml

  <results>
        <result>
            <location>/tmp/path1</location>
            <name>name1</name>
        </result>
        <result>
            <location>/tmp/path2</location>
            <name>name2</name>
        </result>
    </results>

我想遍历所有结果对象,并从每个对象中使用 locationname。 我正在使用以下代码获取结果对象列表

XPathExpression expression = XPathFactory.newInstance().newXPath().compile("/results/result");
NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET); 
for (int i = 0; i < nodes.getLength(); i++) {
  Node node = nodes.item(i);
  // ??
}

如何从节点获取locationname 的值?

【问题讨论】:

    标签: java xml xpath child-nodes


    【解决方案1】:

    您可以像这样获取值。还有其他可能性。不过我没有优化代码。

    XPathExpression expression = XPathFactory.newInstance().newXPath().compile("/results/result");
    NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET); 
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        String location = XPathFactory.newInstance().newXPath().evaluate("location", DomSource(node));
        String name = XPathFactory.newInstance().newXPath().evaluate("name", new DomSource(node));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多