解析xml

来源:互联网 发布:sal软件下载 编辑:程序博客网 时间:2024/05/22 12:09
public Map<String, String> parseXml(String xml) {

Map<String,String> info = new HashMap<String,String>();
        try {
        //得到解析器  
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
DocumentBuilder builder = factory.newDocumentBuilder(); 
StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
//通过解析器就可以得到代表整个内存中XML的Document对象  
Document document = builder.parse(is); 

Element root = document.getDocumentElement();
NodeList list = root.getChildNodes();

for(int i=0;i<list.getLength();i++){
Node node = list.item(i);
if(node.getNodeType()==Node.ELEMENT_NODE){  
info.put(node.getNodeName(), node.getTextContent());
 } 
}
} catch (DOMException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return info;
}
0 0