dom4j 通过 org.dom4j.XPath 设置命名空间来支持 带namespace 的 xpath

测试文件 test.xml

<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.0modelVersion>
    <groupId>cn.znogroupId>
    <artifactId>z-testartifactId>
    <version>0.0.1-SNAPSHOTversion>

    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>xmlunitgroupId>
            <artifactId>xmlunitartifactId>
            <version>1.6version>
            <scope>testscope>
        dependency>

    dependencies>
project>
test.xml

 

所需依赖

    <dependencies>
        <dependency>
            <groupId>dom4jgroupId>
            <artifactId>dom4jartifactId>
            <version>1.6.1version>
        dependency>
        <dependency>
            <groupId>jaxengroupId>
            <artifactId>jaxenartifactId>
            <version>1.1.6version>
        dependency>
    dependencies>

 

测试代码

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.transform.TransformerFactoryConfigurationError;

import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.xpath.DefaultXPath;

public class Dom4jDemo {

    public static void main(String[] args) throws TransformerFactoryConfigurationError, Exception {
        InputStream is = Dom4jDemo.class.getResourceAsStream("/test.xml");

        SAXReader saxReader = new SAXReader();
        Map namespaceURIs = new HashMap();
        namespaceURIs.put("a", "http://maven.apache.org/POM/4.0.0");
        namespaceURIs.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        Document doc = saxReader.read(is);
        
        XPath xpath = new DefaultXPath("//a:project/a:dependencies/a:dependency[a:groupId/text()='junit' and a:artifactId/text()='junit']/a:version");
        xpath.setNamespaceURIs(namespaceURIs);
        Node versionNode = xpath.selectSingleNode(doc);
        
        System.out.println(versionNode.getText());

    }
}

 

输出结果

4.12

 

注意:

1) XPath 是 org.dom4j.XPath

2) select 时的入参是上下文,比如 a node or a list of nodes

3)与 DocumentFactory 设置命名空间不同之处,XPath 可应用于多个document

4)org.dom4j.XPath 只有一个实现类 DefaultXPath

dom4j 通过 org.dom4j.XPath 设置命名空间来支持 带namespace 的 xpath_第1张图片 dom4j 通过 org.dom4j.XPath 设置命名空间来支持 带namespace 的 xpath_第2张图片

 

转载于:https://www.cnblogs.com/zno2/p/7469193.html

你可能感兴趣的:(dom4j 通过 org.dom4j.XPath 设置命名空间来支持 带namespace 的 xpath)