本文介绍了如何将字符串xml转换为Map< String,String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将xml的元素和属性的所有值转换为字符串的映射?
有没有可以做到这一点的图书馆?我发现库xStream,但我不知道如何配置它。
How I can convert all value of element and attributes of xml to Map of string ?Is there some library which can do this ? I found library xStream but I dont know how to configure it.
推荐答案
我只想这样:
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;
}
这篇关于如何将字符串xml转换为Map< String,String>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!