java解析xml,不使用第三方包
解决方法:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header/><soap:Body><ns2:sendMsgResponse xmlns:ns2="http://juchen.webservice.com/"><_return><entry><key>bat</key><value xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">19030816161728700000022</value></entry><entry><key>resp</key><value xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">0</value></entry></_return></ns2:sendMsgResponse></soap:Body></soap:Envelope>
解析xml,把entry标签中的key和value封装成map对象:
Map<String, String> data = new HashMap<String, String>();
try {
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();;
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("entry");
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
for (int i=0;i<nodeList.getLength();i++){
data.put(doc.getElementsByTagName("key").item(i).getFirstChild().getNodeValue(), doc.getElementsByTagName("value").item(i).getFirstChild()!
=null?doc.getElementsByTagName("value").item(i).getFirstChild().getNodeValue():"");
}
}
stream.close();
} catch (Exception ex) {
ex.printStackTrace();
}