如何将xml的元素和属性的所有值转换为字符串的Map? 有些图书馆可以做到这一点吗?我找到了库xStream,但我不知道如何配置它。
答案 0 :(得分:6)
我只是想这样:
public static Map<String, String> convertNodesFromXml(String xml) throws Exception {
InputStream is = new ByteArrayInputStream(xml.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(is);
return createMap(document.getDocumentElement());
}
public static Map<String, String> createMap(Node node) {
Map<String, String> map = new HashMap<String, String>();
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.hasAttributes()) {
for (int j = 0; j < currentNode.getAttributes().getLength(); j++) {
Node item = currentNode.getAttributes().item(i);
map.put(item.getNodeName(), item.getTextContent());
}
}
if (node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
map.putAll(createMap(currentNode));
} else if (node.getFirstChild().getNodeType() == Node.TEXT_NODE) {
map.put(node.getLocalName(), node.getTextContent());
}
}
return map;
}
答案 1 :(得分:1)
Underscore-java库可以将HashMap转换为xml,反之亦然。我是该项目的维护者。
代码示例:
import com.github.underscore.lodash.U;
import java.util.*;
public class Main {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("name", "chris");
map.put("island", "faranga");
System.out.println(U.toXml(map));
Map<String, Object> newMap = (Map<String, Object>) U.fromXml(U.toXml(map));
System.out.println(newMap.get("name"));
}
}
答案 2 :(得分:0)
尝试以下代码:
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("C://logs//XML.xml");
NodeList nodeList = doc.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node textChild = nodeList.item(i);
NodeList childNodes = textChild.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node grantChild = childNodes.item(j);
NodeList grantChildNodes = grantChild.getChildNodes();
for (int k = 0; k < grantChildNodes.getLength(); k++) {
if(!StrUtl.isEmptyTrimmed( grantChildNodes.item(k).getTextContent() ) ) {
Map<String, String> map = new HashMap<String, String>();
map.put(grantChildNodes.item(k).getNodeName() , grantChildNodes.item(k).getTextContent());
System.out.println(map);
}
}
}
}
}catch (Exception e){
e.printStackTrace();
}