dom4j解析xml

来源:互联网 发布:知乎 汽车金融风控 编辑:程序博客网 时间:2024/06/09 15:15

注:本人参考这位大神的代码链接在此
改程序需要dom4j.jarjar包下载地址

package com.xie.studyXml;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.Element;public class Sxm01 {public static void main(String[] args) {        String xmlString = "<html>" + "<head>" + "<title>dom4j解析一个例子</title>" + "<script>"                + "<username>xiexx</username>" + "<password>123456</password>" + "</script>" + "</head>" + "<body>"                + "<result>0</result>" + "<form>" + "<balance>1000</balance>" + "<subID>36242519880716</subID>"                + "</form>" + "</body>" + "</html>";        Map map=xmltoMap(xmlString);        Iterator mes=map.keySet().iterator();        while(mes.hasNext()){            String key=mes.next().toString();            String value=map.get(key).toString();            System.out.println(key+" : "+value);        }}public static Map xmltoMap(String xml){    Document doc=null;    Map<String,String> map=new HashMap<>();    try {        //将字符串转化为XML        doc=DocumentHelper.parseText(xml);        //获取根节点        Element rootElt=doc.getRootElement();        System.out.println("根节点名字:"+rootElt.getName());        //获取跟节点下的子节点        Iterator iter=rootElt.elementIterator("head");        //遍历head节点        while(iter.hasNext()){            Element hea=(Element) iter.next();            String title=hea.elementTextTrim("title");            map.put("title", title);            Iterator scr=hea.elementIterator("script");            while(scr.hasNext()){                Element scra=(Element) scr.next();                String username=scra.elementTextTrim("username");                map.put("username", username);                String password=scra.elementTextTrim("password");                map.put("password",password);            }        }        Iterator body=rootElt.elementIterator("body");        //遍历body节点        while(body.hasNext()){            Element body1=(Element) body.next();            String result=body1.elementTextTrim("result");            map.put("result", result);            Iterator fro=body1.elementIterator("form");            while(fro.hasNext()){                Element fro1=(Element) fro.next();                String balance=fro1.elementTextTrim("balance");                String subID=fro1.elementTextTrim("subID");                map.put("balance", balance);                map.put("subID", subID);            }        }    } catch (DocumentException e) {        e.printStackTrace();    }    return map;}}
1 0