【问题标题】:What is the correct XPath expression for element with attributes?具有属性的元素的正确 XPath 表达式是什么?
【发布时间】:2015-12-17 17:16:26
【问题描述】:

我有 XML 文档,下面有片段

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>myapp.applications</groupId>
        <artifactId>myartifact</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

我想选择groupId 的值,类似于

xml.xpath("//project/parent/groupId").text

这不是所有属性的结果。我想。

如果将文档更改为

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>myapp.applications</groupId>
        <artifactId>myartifact</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

确实有效。

看来 XPath 表达式对于具有属性的项目元素无效。

什么是正确的 XPath 表达式?

【问题讨论】:

    标签: xml xpath


    【解决方案1】:

    问题在于xmlns“属性”不是属性,它们是命名空间定义。元素 //project 表示“在空命名空间中的项目”,但您的 project 位于非空命名空间中。您需要使用前缀注册命名空间(语法取决于您使用的语言),然后使用

    //p:project/p:parent/p:groupId
    

    【讨论】:

    • 我正在使用 Nokogiri Rubygem。有了这个答案,我能够找到像使用这个remove_namespaces的方法一样简单的解决方案
    【解决方案2】:

    1 你可以在根目录下使用:

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    

    2 也这样做

    builderFactory.setNamespaceAware(true);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    

    3 然后

    String expression="//project/parent/groupId";
    
    XPath xpath = XPathFactory.newInstance().newXPath();
    NamespaceContext ctx = new NamespaceContext() {
        public String getNamespaceURI(String prefix) {
            if (prefix == null) throw new NullPointerException("Null prefix");
            return XMLConstants.NULL_NS_URI;
        }
        public String getPrefix(String uri) {
            throw new UnsupportedOperationException();
        }
        public Iterator getPrefixes(String uri) {
            throw new UnsupportedOperationException();
        }
    };
    xpath.setNamespaceContext(ctx);
    XPathExpression expr = xpath.compile(expression) ; 
    
    NodeList nodes  = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
    

    有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多