M87星云

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

JAVA XML 解析功能

复制代码
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Properties;

public class XmlUtils {

    /**
     * 获取根标签,以及一级标签,比如
     * <root>
     *     <name>lily</name>
     *     <age>lily</age>
     * </root>
     *
     * 注:如果标签层级比较深,需要嵌套遍历获取
     *
     * @param xml
     * @return
     * @throws Exception
     */
    public static Properties convertXmlToProperties(String xml) throws Exception {
        Properties properties = new Properties();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream is = new ByteArrayInputStream(xml.getBytes());
        Document document = builder.parse(is);
        Element root = document.getDocumentElement();
        NodeList nodes = root.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            if (nodes.item(i) instanceof Element) {
                Element element = (Element) nodes.item(i);
                String key = element.getTagName();
                String value = element.getTextContent();
                properties.setProperty(key, value);
            }
        }
        return properties;
    }

}
复制代码

 

posted on   挽留匆匆的美丽  阅读(7)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
历史上的今天:
2021-06-03 08、linux 安装 nginx
2021-06-03 09、centos7配置静态IP
点击右上角即可分享
微信分享提示