解析复杂的 xml

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/supingemail/article/details/81334087

好记忆不如烂笔头,能记下点东西,就记下点,有时间拿出来看看,也会发觉不一样的感受。

中规中矩的xml解析,都么有个啥,关键是复杂点的xml解析,而且是复杂点的一类xml,结构一样,但是内容完全不同

Demo.xml:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <ResponseMessage xmlns="http://www.iec.ch/TC57/2008/schema/message">
         <Header>
            <Verb>Show</Verb>
            <Noun>OMSFHYCZCJSJ</Noun>
            <User>
               <UserID>DDD系统</UserID>
               <Organization>BRUCE</Organization>
            </User>
            <Property>
               <Name>count</Name>
               <Value>50</Value>
            </Property>
         </Header>
         <Reply>
            <ReplyCode>OK</ReplyCode>
         </Reply>
         <Payload>
            <rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM-generic#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
               <cim:OMSFHYCZCJSJ rdf:ID="OMSFHYCZCJSJ_0">
                  <cim:aaa>ZHOGNG</cim:aaa>
                  <cim:bbb>广州</cim:bbb>
                  <cim:ccc>2018年第23周 (06.04~06.10)</cim:ccc>
                  <cim:ddd>16500</cim:ddd>
                  <cim:eee>8800</cim:eee>
                  <cim:fff>2200000</cim:fff>
                  <cim:ggg>0</cim:ggg>
                  <cim:hhh>0</cim:hhh>
                  <cim:kkk>16500</cim:kkk>
                  <cim:mmm>2200000</cim:mmm>
               </cim:OMSFHYCZCJSJ>
            </rdf:RDF>
         </Payload>
      </ResponseMessage>
   </soapenv:Body>
</soapenv:Envelope>

提供公共解析,如何公共解析,

即编写公共的获取xml值的方法。具体看码:

    /**
     * 结果集.
     */
    public static Map<String,Map<String, String>> xmlDataMaps=new LinkedHashMap<String,Map<String, String>>();
    /**
     * 节点个数.
     */
    private static Map<String, String> nodeMap=new HashMap<String,String>();
    
    /**
     * 通过字符串获得结果.
     * @param strVal:xml 字符串
     * @param nodeName:节点名称
     */
    public static void getXmlValByStr(String strVal,String nodeName) {
        if (strVal==null || strVal.length()==0) {
            return;
        }
        SAXReader sax = new SAXReader();
        Document document = null;
        try {
            InputStream stream=new ByteArrayInputStream(strVal.getBytes(Constant.ENCODING));
            document = sax.read(stream);
            document.setXMLEncoding(Constant.ENCODING);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        //获得节点个数.
        getXmlNodes(root,nodeName);
        int nodes=nodeMap.size();
        //初始化map集合
        initMaps(nodes);
        //获得数据.
        getXmlNodesVal(root,nodeName);
    }
    
    /**
     * 通过流获得结果.
     * @param stream:流对象
     * @param nodeName:节点名称
     */
    public static void getXmlValByStream(InputStream stream,String nodeName) {
        if (stream==null) {
            return;
        }
        SAXReader sax = new SAXReader();
        Document document = null;
        try {
            document = sax.read(stream);
            document.setXMLEncoding(Constant.ENCODING);
        }
        catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        //获得节点个数.
        getXmlNodes(root,nodeName);
        int nodes=nodeMap.size();
        //初始化map集合
        initMaps(nodes);
        //获得数据.
        getXmlNodesVal(root,nodeName);
    }
    
    /**
     * 通过文件获得对象.
     * @param filePath:文件绝对路径
     * @param nodeName:节点名称
     */
    public static void getXmlValByFile(String filePath,String nodeName) {
        if (filePath==null || filePath.length()==0) {
            return;
        }
        SAXReader sax = new SAXReader();
        File file=new File(filePath);
        Document document = null;
        try {
            document = sax.read(file);
            document.setXMLEncoding(Constant.ENCODING);
        }
        catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        //获得节点个数.
        getXmlNodes(root,nodeName);
        int nodes=nodeMap.size();
        //初始化map集合
        initMaps(nodes);
        //获得数据.
        getXmlNodesVal(root,nodeName);
    }

    /**
     * 初始化map集合.
     * @param nodes:节点数据.
     */
    private static void initMaps(int nodes) {
        for (int i = 0; i < nodes; i++) {
            Map<String, String> tempValMap=new LinkedHashMap<>();
            xmlDataMaps.put(Constant.MAPTAG+i,tempValMap);
        }
    } 
    
    /**
     * 递归遍历所有子节点value
     * @param node
     * @param nodeName
     */
    @SuppressWarnings("unchecked")
    private static void getXmlNodesVal(Element node,String nodeName) {
        String tagName=node.getName();
        String tagVal=node.getTextTrim();
        String attrName ="";
        String attrValue ="";
        List<Attribute> listAttrs = node.attributes();
        for (Attribute attribute : listAttrs) {
            attrName=attribute.getName();
            attrValue=attribute.getValue();
        }
        if (tagName.equalsIgnoreCase(nodeName) && attrName.equalsIgnoreCase("ID")) {
            Map<String, String> actualVals=new LinkedHashMap<String, String>();
            String prex=nodeName+Constant.TAG;
            String key=attrValue.substring(prex.length(), attrValue.length());
            List<Element> listElement = node.elements();
            for (Element element : listElement) {
                 tagName=element.getName();
                 tagVal=element.getTextTrim();
                 actualVals.put(tagName, tagVal);
            }
            xmlDataMaps.put(Constant.MAPTAG+key,actualVals);
        }
        List<Element> listElement = node.elements();
        for (Element element : listElement) {
            getXmlNodesVal(element,nodeName);
        }
    }

    /**
     * 获得节点的个数.
     * @param root
     * @param nodeName
     * @return
     */
    @SuppressWarnings("unchecked")
    private static void getXmlNodes(Element root,String nodeName) {
        String tagName=root.getName();
        String attrName ="";
        String attrValue ="";
        List<Attribute> listAttrs = root.attributes();
        for (Attribute attribute : listAttrs) {
            attrName=attribute.getName();
            attrValue=attribute.getValue();
        }
        if (tagName.equalsIgnoreCase(nodeName) && attrName.equalsIgnoreCase("ID") && attrValue.contains(nodeName)) {
            String prex=nodeName+Constant.TAG;
            String key=attrValue.substring(prex.length(), attrValue.length());
            nodeMap.put(key,attrValue);
        }
        List<Element> listElement = root.elements();
        for (Element element : listElement) {
            getXmlNodes(element,nodeName);
        }
    }
    
    /**
     * 清除内存中的数据.
     */
    public static void clearData() {
        nodeMap.clear();
        xmlDataMaps.clear();
    }

如此就可以将某类复杂的xml解析完成了,并获将获得的值以key,value 的方式保存起来。

猜你喜欢

转载自blog.csdn.net/supingemail/article/details/81334087