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