java解析xml字符串工具类

实现功能

  • 解析xml对应字符串,获取List 根据List的子节点 获取xml包含的全部信息
  • 返回List中所有一级子节点的名称
  • 递归返回List中所有节点

注意:入参字符串一定要包含节点

定义节点类

@Data
    public static class Node {
        private String name;
        private String value;
        private List<Node> children = new ArrayList<>();
        private List<Node> attributes = new ArrayList<>();
        private Node parent;

        public Node(String name, String value) {
            this.name = name;
            this.value = value;
        }

        // 遍历获取所有子节点的名称
        public List<String> getAllNames() {
            List<String> allNames = new ArrayList<>();
            collectAllNames(this, allNames);
            return allNames;
        }

        private void collectAllNames(Node node, List<String> allNames) {
            allNames.add(node.getName());
            for (Node child : node.getChildren()) {
                collectAllNames(child, allNames);
            }
        }

        public List<Node> getChildrenByName(String name) {
            List<Node> nodes = new ArrayList<>();
            for (Node node : children) {
                if (node.name.equals(name)) {
                    nodes.add(node);
                }
            }
            return nodes;
        }

        @Override
        public String toString() {
            return "Node{" +
                "name='" + name + '\'' +
                ", value='" + value + '\'' +
                ", attributes=" + attributesToString(attributes) +
                ", children=" + childrenToString(children) +
                '}';
        }

        private String attributesToString(List<Node> attributes) {
            if (attributes == null || attributes.isEmpty()) {
                return "[]";
            }

            StringBuilder result = new StringBuilder("[");
            for (Node attribute : attributes) {
                result.append(attribute.getName()).append("=").append(attribute.getValue()).append(", ");
            }
            result.delete(result.length() - 2, result.length());
            result.append("]");
            return result.toString();
        }

        private String childrenToString(List<Node> children) {
            if (children == null || children.isEmpty()) {
                return "[]";
            }

            StringBuilder result = new StringBuilder("[");
            for (Node child : children) {
                result.append(child.toString()).append(", ");
            }
            result.delete(result.length() - 2, result.length());
            result.append("]");
            return result.toString();
        }
    }

工具类

package com.zhaxd.common.toolkit;

import lombok.Data;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * XMLUtils
 *
 * @author ZP
 * @since 2023/11/10 17:30
 */
public class XmlUtils {

    public static List<Node> getNodes(String xmlStr) {
        List<Node> nodeList = new ArrayList<>();
        if (xmlStr == null || xmlStr.length() == 0) {
            return nodeList;
        }

        try {
            Document document = parseXmlString(xmlStr);
            if (document != null) {
                Element root = document.getDocumentElement();
                parseXmlNode(root, null, nodeList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return nodeList;
    }


    /**
     * 返回List<Node>中所有一级子节点的名称
     *
     * @param List<Node> nodeList
     * @return Set<String>
     */
    public static Set<String> getChildrenNamesFromNodes(List<Node> nodeList) {
        Set<String> allNames = new HashSet<>();
        for (Node node : nodeList) {
            allNames.addAll(node.getAllNames());
        }
        return allNames;
    }


    /**
     * 返回List<Node>中所有子节点,包括子节点的子节点
     *
     * @param List<Node> nodeList
     * @return Set<String>
     */
    public static List<Node> getAllDescendantsFromNodes(List<Node> nodeList) {
        List<Node> allDescendants = new ArrayList<>();
        for (Node node : nodeList) {
            collectAllDescendants(node, allDescendants);
        }
        return allDescendants;
    }


    private static void collectAllDescendants(Node node, List<Node> allDescendants) {
        allDescendants.add(node);
        for (Node child : node.getChildren()) {
            collectAllDescendants(child, allDescendants);
        }
    }


    private static Document parseXmlString(String xmlString) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(new InputSource(new StringReader(xmlString)));
    }

    private static void parseXmlNode(Element element, Node parent, List<Node> nodeList) {
        Node node = new Node(element.getNodeName(), element.getTextContent().trim());
        node.attributes = getAttributes(element);
        node.parent = parent;
        nodeList.add(node);

        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i) instanceof Element) {
                Element childElement = (Element) children.item(i);
                parseXmlNode(childElement, node, node.getChildren());
            }
        }
    }

    private static List<Node> getAttributes(Element element) {
        List<Node> attributes = new ArrayList<>();
        NamedNodeMap attributeNodes = element.getAttributes();
        for (int i = 0; i < attributeNodes.getLength(); i++) {
            org.w3c.dom.Node attributeNode = attributeNodes.item(i);
            if (attributeNode instanceof Element) {
                Element attributeElement = (Element) attributeNode;
                Node attribute = new Node(attributeElement.getNodeName(), attributeElement.getTextContent().trim());
                attributes.add(attribute);
            }
        }
        return attributes;
    }

    // 定义类保存xml的节点信息
    @Data
    public static class Node {
        private String name;
        private String value;
        private List<Node> children = new ArrayList<>();
        private List<Node> attributes = new ArrayList<>();
        private Node parent;

        public Node(String name, String value) {
            this.name = name;
            this.value = value;
        }

        // 遍历获取所有子节点的名称
        public List<String> getAllNames() {
            List<String> allNames = new ArrayList<>();
            collectAllNames(this, allNames);
            return allNames;
        }

        private void collectAllNames(Node node, List<String> allNames) {
            allNames.add(node.getName());
            for (Node child : node.getChildren()) {
                collectAllNames(child, allNames);
            }
        }

        public List<Node> getChildrenByName(String name) {
            List<Node> nodes = new ArrayList<>();
            for (Node node : children) {
                if (node.name.equals(name)) {
                    nodes.add(node);
                }
            }
            return nodes;
        }

        @Override
        public String toString() {
            return "Node{" +
                "name='" + name + '\'' +
                ", value='" + value + '\'' +
                ", attributes=" + attributesToString(attributes) +
                ", children=" + childrenToString(children) +
                '}';
        }

        private String attributesToString(List<Node> attributes) {
            if (attributes == null || attributes.isEmpty()) {
                return "[]";
            }

            StringBuilder result = new StringBuilder("[");
            for (Node attribute : attributes) {
                result.append(attribute.getName()).append("=").append(attribute.getValue()).append(", ");
            }
            result.delete(result.length() - 2, result.length());
            result.append("]");
            return result.toString();
        }

        private String childrenToString(List<Node> children) {
            if (children == null || children.isEmpty()) {
                return "[]";
            }

            StringBuilder result = new StringBuilder("[");
            for (Node child : children) {
                result.append(child.toString()).append(", ");
            }
            result.delete(result.length() - 2, result.length());
            result.append("]");
            return result.toString();
        }
    }
}


3.使用示例

入参:

<root>    
    <connection>测试达梦</connection>
    <schema/>
    <table>TEST1</table>
    <commit>1000</commit>
    <truncate>N</truncate>
    <ignore_errors>N</ignore_errors>
    <use_batch>Y</use_batch>
    <specify_fields>Y</specify_fields>
    <partitioning_enabled>N</partitioning_enabled>
    <partitioning_field/>
    <partitioning_daily>N</partitioning_daily>
    <partitioning_monthly>Y</partitioning_monthly>
    <tablename_in_field>N</tablename_in_field>
    <tablename_field/>
    <tablename_in_table>Y</tablename_in_table>
    <return_keys>N</return_keys>
    <return_field/>
    <fields>
        <field>
          <column_name>TYPE1</column_name>
          <stream_name>type</stream_name>
        </field>
    </fields>
</root>

调用XmlUtils.getNodes返回

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用dom4j封装的工具类来实现Java解析XML字符串转Map的功能。具体步骤如下: 1.引入dom4j和jaxen的依赖包。 2.编写XmlUtils工具类,实现xmlParser方法,该方法接收两个参数,一个是xml字符串,一个是根节点名称,返回一个Map类型的结果。 ```java import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class XmlUtils { public static Map<String, Object> xmlParser(String xml, String rootName) throws DocumentException { Map<String, Object> map = new HashMap<String, Object>(); SAXReader reader = new SAXReader(); Document document = reader.read(new ByteArrayInputStream(xml.getBytes())); Element root = document.getRootElement(); if (root.getName().equals(rootName)) { map.put(root.getName(), parseElement(root)); } return map; } private static Map<String, Object> parseElement(Element element) { Map<String, Object> map = new HashMap<String, Object>(); List<Attribute> attributes = element.attributes(); for (Attribute attribute : attributes) { map.put("->" + element.getName() + "=>" + attribute.getName(), attribute.getValue()); } List<Element> elements = element.elements(); if (elements.size() == 0) { map.put("->" + element.getName(), element.getTextTrim()); } else { for (Element ele : elements) { if (ele.elements().size() == 0) { map.put("->" + element.getName() + "->" + ele.getName(), ele.getTextTrim()); } else { map.put("->" + element.getName() + "->" + ele.getName(), parseElement(ele)); } } } return map; } } ``` 3.在需要解析XML字符串的地方,调用xmlParser方法即可。 ```java String xml = "<root><name>张三</name><age>18</age><address><province>广东</province><city>深圳</city></address></root>"; Map<String, Object> map = XmlUtils.xmlParser(xml, "root"); System.out.println(map); ``` 输出结果为: ```java {root={->name=张三, ->age=18, ->address={->province=广东, ->city=深圳}}} ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值