Java XML字符串转Map:高效解析方法和示例代码
要将XML格式字符串转换为Map对象,可以使用Java中的DOM解析器来实现。下面是一个示例代码:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;
public class XmlToMap {
public static void main(String[] args) {
String xml = '<root><name>John</name><age>30</age><gender>Male</gender></root>';
Map<String, String> map = xmlToMap(xml);
System.out.println(map);
}
public static Map<String, String> xmlToMap(String xml) {
Map<String, String> map = new HashMap<>();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(xml.getBytes()));
Element root = document.getDocumentElement();
NodeList nodeList = root.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String key = element.getTagName();
String value = element.getTextContent();
map.put(key, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
以上代码将XML字符串<root><name>John</name><age>30</age><gender>Male</gender></root>转换为Map对象,并输出结果为{name=John, age=30, gender=Male}。
原文地址: https://www.cveoy.top/t/topic/pcvj 著作权归作者所有。请勿转载和采集!