0
点赞
收藏
分享

微信扫一扫

xml-Java+dom4j实现工具类解析xml文件、标签、属性内容xpath检索

sunflower821 04-04 22:00 阅读 2

〇、相关资料

1、Maven项目使用DOM4J

Maven项目使用DOM4J_dom4j maven-CSDN博客

2、Dom4J解析XML、Xpath检索XML

Dom4J解析XML、Xpath检索XML_dom4j官网-CSDN博客


一、环境准备

1、下载依赖

<dependency>
  <groupId>dom4j</groupId>
  <artifactId>dom4j</artifactId>
  <version>1.6.1</version>
</dependency>
<dependency>
  <groupId>jaxen</groupId>
  <artifactId>jaxen</artifactId>
  <version>1.1.6</version>
</dependency>

2、示例xml文件准备

背景:webservice

<?xml version='1.0' encoding='UTF-8'?><wsdl:definitions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://crm.service.boulderai.com" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:ns2="http://schemas.xmlsoap.org/soap/http" xmlns:ns1="http://erp.service.boulderai.com" name="PurchaseService" targetNamespace="http://crm.service.boulderai.com">
  <wsdl:import location="http://172.16.21.131:8080/myService/purchase?wsdl=PurchaseService.wsdl" namespace="http://erp.service.boulderai.com">
    </wsdl:import>
  <wsdl:binding name="PurchaseServiceSoapBinding" type="ns1:PurchaseService">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="saveBatch">
      <soap:operation soapAction="" style="document"/>
      <wsdl:input name="saveBatch">
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output name="saveBatchResponse">
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
    <wsdl:operation name="findById">
      <soap:operation soapAction="" style="document"/>
      <wsdl:input name="findById">
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output name="findByIdResponse">
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
    <wsdl:operation name="getPurchaseOrderList">
      <soap:operation soapAction="" style="document"/>
      <wsdl:input name="getPurchaseOrderList">
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output name="getPurchaseOrderListResponse">
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
    <wsdl:operation name="saveOne">
      <soap:operation soapAction="" style="document"/>
      <wsdl:input name="saveOne">
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output name="saveOneResponse">
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="PurchaseService">
    <wsdl:port binding="tns:PurchaseServiceSoapBinding" name="PurchaseServiceImplPort">
      <soap:address location="http://172.16.21.131:8080/myService/purchase"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>


二、代码编写

1、工具类

package com.gemenyaofei.integration.app.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


public class XmlParseUtils {

    /**
     * xml转json
     *
     * @param xmlContent
     * @return
     */
    public static String xml2jsonStr(String xmlContent) {
        try {
            // 创建XML Mapper
            XmlMapper xmlMapper = new XmlMapper();
            // 从XML字符串读取数据并解析为JsonNode
            JsonNode jsonNode = xmlMapper.readTree(xmlContent);
            // 创建JSON Mapper
            ObjectMapper jsonMapper = new ObjectMapper();
            // 将JsonNode转换为JSON字符串
            String json = jsonMapper.writeValueAsString(jsonNode);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * xml文件转内容
     *
     * @param path
     * @return
     */
    public static String xmlFile2Content(String path) {
        try {
            return new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * xml内容转dom4j的Document对象
     *
     * @param content
     * @return
     */
    public static Document xmlStr2Document(String content) {
        Document document = null;
        try {
            document = DocumentHelper.parseText(content);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        return document;
    }

    /**
     * 查找根节点的属性信息
     *
     * @param content
     * @param attribute
     * @return
     */
    public static String getRootAttrVal(String content, String attribute) {
        Document document = xmlStr2Document(content);
        Element root = document.getRootElement();
        Namespace namespaceForPrefix = root.getNamespaceForPrefix(attribute);
        return Objects.nonNull(namespaceForPrefix) ? namespaceForPrefix.getURI() :
                Objects.nonNull(root.attribute(attribute)) ? root.attribute(attribute).getValue() :
                        null;
    }

    public static List<String> getAttrVal(String content, String xpathExpression) {
        Document document = xmlStr2Document(content);
        List<Node> nodes = document.selectNodes(xpathExpression);
        List<String> resultValue = new ArrayList<>();
        for (Node node : nodes) {
            if (node instanceof org.dom4j.Attribute) {
                org.dom4j.Attribute attribute = (org.dom4j.Attribute) node;
                resultValue.add(attribute.getValue());
            }
        }
        return resultValue;
    }
}


2、测试类

package com.gemenyaofei.integration.app.utils;

import org.dom4j.Document;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

class XmlParseUtilsTest {
    public String filePath = "C:\\Users\\Administrator\\Desktop\\purchase.xml";
    private String content;

    @org.junit.jupiter.api.BeforeEach
    void setUp() {
        content = XmlParseUtils.xmlFile2Content(filePath);
    }

    @org.junit.jupiter.api.AfterEach
    void tearDown() {
    }

    @org.junit.jupiter.api.Test
    void xml2jsonStr() {
    }

    @org.junit.jupiter.api.Test
    void xmlFile2Content() {
        System.out.println(content);
        assertNotNull(content);
    }

    @org.junit.jupiter.api.Test
    void xmlStr2Document() {
        Document document = XmlParseUtils.xmlStr2Document(content);
        assertNotNull(document);
    }

    @org.junit.jupiter.api.Test
    void getRootAttrVal() {
        String rootAttrVal1 = XmlParseUtils.getRootAttrVal(content, "targetNamespace");
        System.out.println(rootAttrVal1);
        assertNotNull(rootAttrVal1);
        String rootAttrVal2 = XmlParseUtils.getRootAttrVal(content, "wsdl");
        System.out.println(rootAttrVal2);
        assertNotNull(rootAttrVal2);
    }

    @org.junit.jupiter.api.Test
    void getAttrVal() {
        List<String> list = XmlParseUtils.getAttrVal(content, "//wsdl:operation/@name");
        list.forEach(System.out::println);
        assertSame(list.size(), 4);
    }
}






举报

相关推荐

0 条评论