Dom4j和Xpath解析xml(包括带有命名空间的xml)

Dom4j和Xpath解析xml(包括带有命名空间的xml)

  • 直接上代码
  • maven
<dependency>
    <groupId>dom4jgroupId>
    <artifactId>dom4jartifactId>
    <version>1.6.1version>
dependency>

<dependency>
    <groupId>jaxengroupId>
    <artifactId>jaxenartifactId>
    <version>1.1.6version>
dependency>
<dependency>
    <groupId>saxpathgroupId>
    <artifactId>saxpathartifactId>
    <version>1.0-FCSversion>
dependency>
  • Java代码
package com.zjb.demo;

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

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;

/**
 * @author zhaojianbo
 * @date 2020-01-16 10:26
 */
public class XmlDemo {
    public static void main(String[] args) throws Exception {
        //存放命名空间
        HashMap<String, String> nameSpaceMap = new HashMap<>();
        //解析器
        SAXReader reader = new SAXReader();
        //路径
        String xmlPath = "D:/test/xml/spring-context.xml";
        File file = new File(xmlPath);
        FileInputStream fInput = new FileInputStream(file);
        //加载文件
        Document document = reader.read(fInput);
        //获取命名空间
        List<Namespace> namespaceList = document.getRootElement().declaredNamespaces();
        //加载命名空间
        for (Namespace namespace : namespaceList) {
            //此处判断可换成StringUtils工具类
            if (namespace.getPrefix() != null && !namespace.getPrefix().equals("")) {
                nameSpaceMap.put(namespace.getPrefix(), namespace.getURI());
            } else {
                String uri = namespace.getURI();
                nameSpaceMap.put(uri.substring(uri.lastIndexOf("/") + 1), uri);
            }
        }
        //节点路径
        String nodePath = "//context:property-placeholder/@location";
        //设置命名空间
        reader.getDocumentFactory().setXPathNamespaceURIs(nameSpaceMap);
        //获取节点内容
        Node node = document.selectSingleNode(nodePath);
        System.out.println(node.getText());
    }
}

你可能感兴趣的:(服务器)