最近一个SN供应商融资平台中需要一个XML与Object(主要是HashMap)互转的java类,代码中主要使用了dom4j类库及递归,在这里发出来与大家共享,鄙人原创。
package com.suning.dom4j; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class ParseXml { private static List elemList = new ArrayList(); private static HashMap hs = new HashMap(); private static String listName; private static Vector vector = new Vector(); private static HashMap tesths = new HashMap(); private static String srcXml = "<root><orderhead><ordercode>450857496</ordercode><ordercode>yangying</ordercode><maker>Haier</maker></orderhead><orderdetails><orderdetail><linenum>10</linenum><productcode>10001</productcode></orderdetail><orderdetail><linenum>20</linenum><productcode>10002</productcode></orderdetail><orderdetail><linenum>30</linenum><productcode>10003</productcode></orderdetail><test>test</test><test>test222</test><test>test333</test></orderdetails></root>"; public static void main(String args[]) throws DocumentException { ParseXml test = new ParseXml(); Element root = test.getRootElement(); tesths = test.getObject(root); String text = parse(null, tesths, null); System.out.println(text); System.out.println("-----------解析结果------------"); } /** * * 获取根元素 */ public Element getRootElement() throws DocumentException { Document srcdoc = DocumentHelper.parseText(srcXml); Element elem = srcdoc.getRootElement(); return elem; } public HashMap getObject(Element element) { List elementlists = element.elements(); String keyName = element.getName(); HashMap retHas = new HashMap(); if (elementlists.size() == 0) { // 没有子元素 retHas.put(element.getQualifiedName(), element.getTextTrim()); return retHas; } else { HashMap hs = new HashMap(); Vector vector = new Vector(); for (Iterator it = elementlists.iterator(); it.hasNext();) { Element elem = (Element) it.next(); String key = elem.getQualifiedName(); HashMap tempMap = getObject(elem); if (hs.containsKey(key)) { HashMap hsclone = (HashMap) hs.clone(); if (hsclone.get(key) instanceof HashMap) { vector.add(hsclone.get(key)); vector.add(tempMap.get(key)); } else if (hsclone.get(key) instanceof Vector) { vector = (Vector) hsclone.get(key); vector.add(tempMap.get(key)); } else { vector.add(hsclone.get(key)); vector.add(tempMap.get(key)); } Vector vectorclone = (Vector) vector.clone(); vector.clear(); hs.put(key, vectorclone); } else { hs.put(elem.getQualifiedName(), tempMap.get(key)); } } retHas.put(keyName, hs); return retHas; } } public static String parse(Element element, HashMap data, String nodeName) { String key = null; Object value = null; Document document = null; Element child = null; if (element == null) { document = DocumentHelper.createDocument(); } if ((element == null) && (data == null)) { System.out.println("error"); } Iterator iter = data.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); key = (String) entry.getKey(); value = entry.getValue(); if (value instanceof Vector) { Iterator it = ((Vector) value).iterator(); while (it.hasNext()) { Object HM_val = it.next(); if (HM_val instanceof HashMap) { child = element.addElement(key); parse(child != null ? child : element, (HashMap) HM_val, key); } else { child = element.addElement((String) key); child.setText((String) HM_val); } } } else if (value instanceof HashMap) { if (element == null) { element = document.addElement(key); } else { child = element.addElement(key); } parse(child != null ? child : element, (HashMap) value, key); } else { if (element == null) { element = document.addElement(key); element.setText((String) value); } else { child = element.addElement(key); child.setText((String) value); } } } String text = ""; if (element != null) { text = formatXml(element, "GBK", false); } else if (document != null) { text = formatXml(document.getRootElement(), "GBK", false); } System.out.println(text); return text; } public static String formatXml(Element document, String charset, boolean istrans) { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(charset); StringWriter sw = new StringWriter(); XMLWriter xw = new XMLWriter(sw, format); xw.setEscapeText(istrans); try { xw.write(document); xw.flush(); xw.close(); } catch (IOException e) { System.out.println("格式化XML文档发生异常,请检查!"); e.printStackTrace(); } return sw.toString(); } }
1.最后的结果是HashMap
{root={orderdetails={orderdetail=[{productcode=10001, linenum=10}, {productcode=10002, linenum=20}, {productcode=10003, linenum=30}], test=[test, test222, test333]}, orderhead={maker=Haier, ordercode=[450857496, yangying]}}}
2.XML格式是:
<root> <orderdetails> <orderdetail> <productcode>10001</productcode> <linenum>10</linenum> </orderdetail> <orderdetail> <productcode>10002</productcode> <linenum>20</linenum> </orderdetail> <orderdetail> <productcode>10003</productcode> <linenum>30</linenum> </orderdetail> <test>test</test> <test>test222</test> <test>test333</test> </orderdetails> <orderhead> <maker>Haier</maker> <ordercode>450857496</ordercode> <ordercode>yangying</ordercode> </orderhead> </root>