【问题标题】:Java Xpath expressionJava Xpath 表达式
【发布时间】:2023-03-09 13:19:01
【问题描述】:

我有以下 XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://research.sun.com/wadl/2006/10">
<doc xmlns:jersey="http://jersey.dev.java.net/" 
     jersey:generatedBy="Jersey: 1.0.2 02/11/2009 07:45 PM"/>
<resources base="http://localhost:8080/stock/">
    <resource path="categories"> (<<---I want to get here)
        <method id="getCategoriesResource" name="GET">

我想获得resource/@path 的值,所以我有以下Java 代码:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
// get the xml to parse from URI
Document doc = builder.parse(serviceUri + "application.wadl"); 
XPathFactory xfactory = XPathFactory.newInstance();
XPath xpath = xfactory.newXPath();
XPathExpression expression = 
        xpath.compile("/application/resources/resource/@path");
this.baseUri = (String) expression.evaluate(doc, XPathConstants.STRING);

使用此 XPath 表达式,结果 (baseUri) 始终是空字符串 ("")。

【问题讨论】:

  • 我不是 XPath 专家,但你不是只用@attribute 处理属性吗?你有/@path。试试/application/resources/resource@path
  • /application/resources/resource/@path 是处理属性的正确方法

标签: java xml xpath


【解决方案1】:

节点不在空字符串命名空间中,您必须指定它:/wadl:application/wadl:resources/wadl:resource/@path。此外,您应该在 XPath 引擎命名空间上下文中注册命名空间。

这是工作示例:

    xpath.setNamespaceContext(new NamespaceContext()
    {
        @Override
        public String getNamespaceURI(final String prefix)
        {
            if(prefix.equals("wadl"))
                return "http://research.sun.com/wadl/2006/10";
            else
                return null;
        }

        @Override
        public String getPrefix(final String namespaceURI)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public Iterator getPrefixes(final String namespaceURI)
        {
            throw new UnsupportedOperationException();
        }
    });
    XPathExpression expression = xpath.compile("/wadl:application/wadl:resources/wadl:resource/@path");

【讨论】:

  • 您的意思是说节点不在 no 命名空间中。它们位于 default 命名空间中。
猜你喜欢
  • 2012-12-30
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多