xml报文解析

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CameraUtil {

    public static Map xmlElements( String xmlDoc) {
        Map resultMap = new HashMap();//结果Map
        List enterslist = new ArrayList();//进入统计
        List exitslist = new ArrayList();//出去统计

        //创建一个新的字符串
        StringReader read = new StringReader(xmlDoc);
        //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        //创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        try {
            //通过输入源构造一个Document
            Document doc = sb.build(source);
            //取的根元素
            Element root = doc.getRootElement();
            //得到根元素所有子元素的集合
            List jiedian = root.getChildren();
            //获得XML中的命名空间(XML中未定义可不写)
            Namespace ns = root.getNamespace();
            Element et = null;
            for(int i=0;i enterslist, List exitslist){
        if(enterslist.size()<= 0 && exitslist.size() <= 0){
              return 0;
        }else {
            int num = 0;
            for (int i = 0; i < enterslist.size(); i++) {
                num = num + enterslist.get(i);
            }
            for (int i = 0; i < exitslist.size(); i++) {
                num = num - exitslist.get(i);
            }
            return num;
        }
    }
 
/**
 * xml转成map
 * @param xmlStr
 * @return
 */
public static Map xmlStr2Map(String xmlStr){
    Map map = new HashMap();
    Document doc;
    try {
        doc = DocumentHelper.parseText(xmlStr);
        Element root = doc.getRootElement();
        List children = root.elements();
        if(children != null && children.size() > 0) {
            for(int i = 0; i < children.size(); i++) {
                Element child = (Element)children.get(i);
                map.put(child.getName(), child.getTextTrim());
            }
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    log.info("解析出来的map为:{}",map);
    return map;
}
}

你可能感兴趣的:(xml报文解析)