Dom4j把xml转换成Map(固定格式)

/**

* 可解析list

*

* @param fileName

* @return

* @throws Exception

*/

@SuppressWarnings("unchecked")

public Map<String, Object> parserXmlToJSONObjectByArray(String fileName) throws Exception {

// File inputXml = new File(fileName);

InputStream iStream = new ByteArrayInputStream(fileName.getBytes());

SAXReader saxReader = new SAXReader();

Map<String, Object> returnMap = new HashMap<String, Object>();

Reader r = new InputStreamReader(iStream, "UTF-8");

Document document = saxReader.read(r);

Element employees = document.getRootElement();

Map<String, Object> jsontotal = new HashMap<String, Object>();

for (Iterator<?> i = employees.elementIterator(); i.hasNext();) {

Element employee = (Element) i.next();

List<Map<String, Object>> jarry = new ArrayList<Map<String, Object>>();

for (Iterator<?> j = employee.elementIterator(); j.hasNext();) {

Element node = (Element) j.next();

Map<String, Object> jsondetail = new HashMap<String, Object>();

for (Iterator<Element> k = node.elementIterator(); k.hasNext();) {

Element node_child = (Element) k.next();

jsondetail.put(node_child.getName(), node_child.getText());

}

jarry.add(jsondetail);

}

jsontotal.put(employee.getName(), employee.getText());

returnMap.put("jsontotal", jsontotal);

if (jarry != null && jarry.size() > 0) {

returnMap.put("jsonarray", jarry);

}

}

return returnMap;

}

Dom4j把xml转换成Map(非固定格式)

 

将xml转换成Map,能够应对不用结构的xml,而不是只针对固定格式的xml.
转换规则:
1.主要是Map与List的互相嵌套
2.同名称的节点会被装进List

上一篇:多级xml解析方案


下一篇:ActiveMQ使用教程