java xml字符串转map
时间: 2024-02-05 10:05:00 浏览: 87
以下是Java中将XML字符串转换为Map的示例代码:
```java
import java.util.*;
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class XmlToMap {
public static void main(String[] args) throws Exception {
String xmlString = "<root><name>John</name><age>30</age></root>";
Map<String, String> map = xmlToMap(xmlString);
System.out.println(map);
}
public static Map<String, String> xmlToMap(String xmlString) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
Document document = builder.parse(inputStream);
Element root = document.getDocumentElement();
Map<String, String> map = new HashMap<>();
NodeList nodeList = root.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) {
String key = node.getNodeName();
String value = node.getTextContent();
map.put(key, value);
}
}
return map;
}
}
```
这个示例代码中,我们使用Java内置的XML解析器将XML字符串解析为Document对象,然后遍历Document对象的子节点,将节点的名称作为Map的键,节点的文本内容作为Map的值,最终返回一个Map对象。
阅读全文