1. 主要方法
private Map parseXml(String xml) throws DocumentException, IOException { SAXReader reader = new SAXReader(); InputStream in = IOUtils.toInputStream(xml, "UTF-8"); Document doc = reader.read(in); Map map = getParseMapFromXMLStream(doc,"/ContractRoot/TcpCont/Response"); return map; }
public Map getParseMapFromXMLStream(Document doc,String parentPath) throws DocumentException { List rowList = doc.selectNodes(parentPath); Map map = null; List list = null; if(rowList != null && rowList.size() >0) { list = new ArrayList(); for(Iterator iter = rowList.iterator();iter.hasNext();){ map = new HashMap(); //获得具体的节点的父元素 Element element = (Element)iter.next(); //获得具体的节点的父元素的属性 // List elementList = element.attributes(); // for(Iterator iter1 = elementList.iterator();iter1.hasNext();){ // //将每个属性转化为一个抽象属性,然后获取其名字和值 // AbstractAttribute aa = (AbstractAttribute)iter1.next(); // System.out.println("Name:"+aa.getName()+";Value:"+aa.getValue()); // } // 如果element下有子元素,(类似width="**"),要想获得该子元素的值,可以用如下方法 // System.out.println(element.elementText("test")); //获得父节点内的各种借点或者属性 Iterator it1 = element.elementIterator(); while(it1.hasNext()) { Element element1 = (Element)it1.next(); //获得子节点的所有列表 List elementList1 = element1.attributes(); // System.out.println("name is " + element1.getName() + "123 is " + element1.getText()); map.put(element1.getName(), element1.getText()); // list.add(map); // for(Iterator it2 = elementList1.iterator();it2.hasNext();){ // //将每个属性转化为一个抽象属性,然后获取其名字和值 // AbstractAttribute aa = (AbstractAttribute)it2.next(); //// System.out.println("Name11:"+aa.getName()+";Value11:"+aa.getValue()); // //这边需要添加借点的名字为KEY的值(重要) // map.put(element1.getName(), aa.getValue()); // } } } } return map; }
<?xml version="1.0" encoding="UTF-8"?> <ContractRoot> <TcpCont> <TransactionID>600105A002201305031234567890</TransactionID> <ActionCode>1</ActionCode> <RspTime>20130918103343</RspTime> <Response> <RspType>0</RspType> <RspCode>0000</RspCode> <RspDesc>操作成功</RspDesc> <CUST_SO_NUMBER>FJ2013091842549343</CUST_SO_NUMBER> </Response> </TcpCont> <SvcCont/> </ContractRoot>