java - 为什么 XPath namespace-uri() 不能与 Java 开箱即用?

标签 java xml xpath

我正在尝试使用 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));

        }
    }
}

最佳答案

查询看起来不错。您还需要将 DocumentBuilderFactory 声明为“命名空间感知”。

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

关于java - 为什么 XPath namespace-uri() 不能与 Java 开箱即用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7138632/

相关文章:

java - iText/Swing : Breaking text in a box

xml - 使用http在golang中读取FederationMetadata.xml

xml - 使用 XSLT 匹配 XML 文档中的任何节点,即使我不知道节点的名称

java - 编译 XPath 表达式问题

html - Xpath 得到一个如果 href 包含字符串的一部分

java - 如何使用 Lucene 的新 AnalyzingInfixSuggester API 实现自动建议?

java - UTF-8 字符未显示

java - 删除 ArrayList 对象问题

java - JDOM 从根中删除元素

ios - PhoneGap : modify config. xml 添加属性到 Info.plist ion iOS