public static void main(String[] args) throws Exception {
Map<String, Object> sendMap = new HashMap<String, Object>();
String data = "<?xml version=\"1.0\" encoding=\"gb2312\"?><p><seqid></seqid><client>0BF3F2D9A01797BBF05D6BC89877DC91</client><ename>108-wc</ename><code>0</code><msg>成功</msg><totalm>12447.97</totalm><cash>5669.13</cash><stockm>6778.84</stockm><num>2</num><stock><node><market>0</market><symbol>600104</symbol><direct>1</direct><type>0</type><avgprice>21.010</avgprice><holdnum>299</holdnum></node><node><market>0</market><symbol>601818</symbol><direct>1</direct><type>0</type><avgprice>4.993</avgprice><holdnum>4</holdnum></node></stock></p>";
List<Map> nodeList = new ArrayList<Map>();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(data)));
Element root = doc.getDocumentElement();// 根节点
Node node = root.getFirstChild();
while(node != null) {
String nodeName = node.getNodeName().trim();
String nodeValue = node.getTextContent().trim();
if("stock".equals(nodeName) && node.hasChildNodes()) {
Node nodeOne = node.getFirstChild();
while(nodeOne != null) {
String nodeOneName = nodeOne.getNodeName().trim();
if("node".equals(nodeOneName) && nodeOne.hasChildNodes()){
Map<String, Object> nodeMap = new HashMap<String, Object>();
Node threeNode = nodeOne.getFirstChild();
while(threeNode != null) {
nodeMap.put(threeNode.getNodeName(), threeNode.getTextContent());
threeNode = threeNode.getNextSibling();
}
nodeList.add(nodeMap);
}
nodeOne = nodeOne.getNextSibling();
}
}else{
sendMap.put(nodeName, nodeValue);
}
node = node.getNextSibling();
}
sendMap.put("node", nodeList);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sendMap);
}
打印结果:{node=[{direct=1, market=0, symbol=600104, avgprice=21.010, holdnum=299, type=0},
{direct=1, market=0, symbol=601818, avgprice=4.993, holdnum=4, type=0}],
num=2, seqid=, client=0BF3F2D9A01797BBF05D6BC89877DC91, stockm=6778.84, cash=5669.13, ename=108-wc, code=0, totalm=12447.97, msg=成功}
posted on 2015-08-09 10:09
藤本蔷薇 阅读(471)
评论(0) 编辑 收藏