码上敲享录 > java入门知识分享 > java实现XML格式字符串转换为Map

java实现XML格式字符串转换为Map

上一章章节目录下一章 2018-08-09已有6237人阅读 评论(0)

java实现XML格式字符串转换为Map

答:

直接上源码,复制即可使用。

public static Map<String, String> xmlToMap(String strXML) throws Exception {
try {
       Map<String
, String> data = new HashMap<String, String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setExpandEntityReferences(false);
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
//DocumentBuilder documentBuilder = WXPayXmlUtil.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
       for (int idx = 0; idx < nodeList.getLength(); ++idx) {
           Node node = nodeList.item(idx)
;
           if (node.getNodeType() == Node.ELEMENT_NODE) {
               org.w3c.dom.Element element = (org.w3c.dom.Element) node
;
data.put(element.getNodeName(), element.getTextContent());
}
       }
try {
           stream.close()
;
} catch (Exception ex) {
// do nothing
}
return data;
} catch (Exception ex) {
throw ex;
}
}

本文地址:http://www.yayihouse.com/yayishuwu/chapter/1453

1

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交