首页 > 编程语言 >JAVA XML 解析功能

JAVA XML 解析功能

时间:2024-06-03 10:43:35浏览次数:28  
标签:XML xml w3c JAVA Element import nodes 解析 Properties

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;
    }

}

 

标签:XML,xml,w3c,JAVA,Element,import,nodes,解析,Properties
From: https://www.cnblogs.com/M87-A/p/18228326

相关文章