dom4j 使用原生xpath 处理带命名空间的文档

测试文件

<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>
View Code

 

依赖

    <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 javax.xml.transform.TransformerFactoryConfigurationError;

import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class Dom4jDemo {

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

        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read(is);

        Node versionNode = doc.selectSingleNode("//*[local-name()='project']/*[local-name()='version']");

        System.out.println(versionNode.getText());

    }
}

 

结果

0.0.1-SNAPSHOT

 

注意:

1) 这种方法简单的xpath还可以,复杂的不好写

2)详细解读 https://www.w3.org/TR/xpath/

3) xpath的缩写/全称

 

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

你可能感兴趣的:(dom4j 使用原生xpath 处理带命名空间的文档)