原始jdk javax.xml.parsers xml转化总结
以前遇到xml转化问题是一般直接使用了dom4j和jdom,今天尝试了一下使用普通的javax.xml,总结一下
1,xml转化为String
public static String getTextFromDom(Document doc) { TransformerFactory tfFactory = TransformerFactory.newInstance(); Transformer tf; ByteArrayOutputStream bos = null; try { tf = tfFactory.newTransformer(); tf.setOutputProperty("encoding", "UTF-8"); bos = new ByteArrayOutputStream(); tf.transform(new DOMSource(doc), new StreamResult(bos)); } catch (Exception e) { e.printStackTrace(); } return bos.toString(); }
2,符合格式的String 转化为document
public static Document getDocument(String xml) { Document document = null; try { StringReader stringReader = new StringReader(xml); InputSource inputSource = new InputSource(stringReader); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbf.newDocumentBuilder(); document = dBuilder.parse(inputSource); } catch (Exception e) { e.printStackTrace(); } return document; }
3,将xml转化为map(子类如果仍有子类,仍以map形式存,map取值是需判断值是否也是map)
public static Map<String, Object> getMapByDocument(Node node) { if (node.hasChildNodes() && node.getFirstChild().getNodeType()==Document.ELEMENT_NODE) { Map<String, Object> result = new HashMap<String, Object>(); NodeList nl = node.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node childNode = nl.item(i); if(childNode.hasChildNodes() && childNode.getFirstChild().getNodeType()==Document.ELEMENT_NODE){ Map<String, Object> childrenMap = getMapByDocument(childNode); result.put(childNode.getNodeName(), childrenMap); }else { result.put(childNode.getNodeName(), childNode.getTextContent()); } } return result; } return null; }
结果查看
public static void main(String[] args) { String xmlStr = "<body>" + "<ResultCode>6202</ResultCode>" + "<ResultDesc><aa>fffffffffff</aa></ResultDesc>" + "<SmsIds/><RemainCount>0</RemainCount>" + "</body>"; Document doc = getDocument(xmlStr); System.out.println(getTextFromDom(doc)); Map<String, Object> respMap = getMapByDocument(doc); Object result = respMap.get("body"); if (result instanceof java.util.Map) { Map new_name = (Map) result; if (new_name.get("ResultDesc") instanceof java.util.Map) { Map ResultDesc = (Map) new_name.get("ResultDesc"); System.out.println(ResultDesc.get("aa")); } System.out.println(new_name.get("ResultCode")); } for (Object obj : respMap.values()) { System.out.println(obj); } }
结果如下
<?xml version="1.0" encoding="UTF-8" standalone="no"?><body><ResultCode>6202</ResultCode><ResultDesc><aa>fffffffffff</aa></ResultDesc><SmsIds/><RemainCount>0</RemainCount></body> fffffffffff 6202 {ResultDesc={aa=fffffffffff}, ResultCode=6202, SmsIds=, RemainCount=0}