【问题标题】:Why doesn't XPath namespace-uri() work out of the box with Java?为什么 XPath namespace-uri() 不能与 Java 一起使用?
【发布时间】:2011-08-21 13:51:26
【问题描述】:

我正在尝试使用 XPath 中的 namespace-uri() 函数根据节点的完全限定名称检索节点。 this online XPath tester 等中的查询 //*[local-name() = 'customerName' and namespace-uri() = 'http://example.com/officeN'] 正确返回了相关节点。然而,下面的自包含 Java 类不检索任何内容。 namespace-uri() 我做错了什么?

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class Test{
    public static void main(String[] args)throws Exception {

        XPathExpression expr = XPathFactory.newInstance().newXPath().compile(
                "//*[local-name() = 'customerName' and namespace-uri() = 'http://example.com/officeN']");
        String xml=
            "<Agents xmlns:n=\"http://example.com/officeN\">\n"+
            "\t<n:Agent>\n\t\t<n:customerName>Joe Shmo</n:customerName>\n\t</n:Agent>\n"+
            "\t<n:Agent>\n\t\t<n:customerName>Mary Brown</n:customerName>\n\t</n:Agent>\n</Agents>";
        System.out.println(xml);
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
        NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        System.err.println("\n\nNodes:");
        for (int i = 0; i < nodes.getLength(); i++) {
            System.err.println(nodes.item(i));

        }
    }
}

【问题讨论】:

  • 感谢您的这篇文章!对 XPath 使用 namespace-uri 确实很有帮助。

标签: java xml xpath


【解决方案1】:

查询看起来不错。您还需要将 DocumentBuilderFactory 声明为“可识别名称空间”。

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));

【讨论】:

  • 谢谢!这正是我所需要的!
猜你喜欢
  • 1970-01-01
  • 2014-04-24
  • 2019-06-19
  • 1970-01-01
  • 1970-01-01
  • 2010-09-23
  • 2018-03-09
  • 2021-06-14
  • 2012-10-09
相关资源
最近更新 更多