xml字符串转map对象
时间: 2023-09-30 22:12:15 浏览: 49
可以使用Java中的XML解析库来将XML字符串转换为Map对象。以下是一种实现方式:
```java
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.*;
public class XmlToMapConverter {
public static Map<String, Object> xmlToMap(String xmlString) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
Document doc = builder.parse(inputStream);
Element root = doc.getDocumentElement();
return elementToMap(root);
}
private static Map<String, Object> elementToMap(Element element) {
Map<String, Object> map = new LinkedHashMap<>();
NodeList nodes = element.getChildNodes();
if (nodes.getLength() == 1 && nodes.item(0) instanceof Text) {
map.put(element.getNodeName(), element.getTextContent());
return map;
}
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node instanceof Element) {
Element childElement = (Element) node;
Map<String, Object> childMap = elementToMap(childElement);
String nodeName = childElement.getNodeName();
if (map.containsKey(nodeName)) {
Object existingValue = map.get(nodeName);
if (existingValue instanceof List) {
((List<Object>) existingValue).add(childMap);
} else {
List<Object> newList = new ArrayList<>();
newList.add(existingValue);
newList.add(childMap);
map.put(nodeName, newList);
}
} else {
map.put(nodeName, childMap);
}
}
}
return map;
}
}
```
你可以使用`xmlToMap`方法来将XML字符串转换为Map对象。以下是一个示例:
```java
String xmlString = "<root><name>John</name><age>30</age></root>";
Map<String, Object> map = XmlToMapConverter.xmlToMap(xmlString);
System.out.println(map);
```
输出结果为:
```
{root={name=John, age=30}}
```
请注意,此实现假设XML中没有重复的节点名称。如果XML中存在重复的节点名称,可以使用`List<Object>`来保存相同节点名称的多个值。