悠然哈哈哈

导航

解析XML

import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class Test {

public static void main(String[] args) {
Test t=new Test();
String xmlPath = "src/pay.xml";
Map<String, Object> map=t.getFamilyMemebers(xmlPath);
System.out.println(map.get("appid"));
}

public Map<String, Object> getFamilyMemebers(String xmlPath){
Map<String, Object> map=new HashMap<String, Object>();
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(true);
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlPath); // 使用dom解析xml文件

NodeList sonlist = doc.getElementsByTagName("WeChat");
for (int i = 0; i < sonlist.getLength(); i++) // 循环处理对象
{
Element son = (Element)sonlist.item(i);;

for (Node node = son.getFirstChild(); node != null; node = node.getNextSibling()){
if (node.getNodeType() == Node.ELEMENT_NODE){
String name = node.getNodeName();
String value = node.getFirstChild().getNodeValue();
// System.out.println(name+" : "+value);
map.put(name, value);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?><father>
<Alipay></Alipay>
<WeChat>
<appid>a</appid>
<mchid>b</mchid>
<partnerkey>c</partnerkey>
<notifyurl>d</notifyurl>
</WeChat>
</father>

posted on 2015-09-21 15:10  悠然886  阅读(162)  评论(0编辑  收藏  举报