• [ java 工具类] xml字符串解析成Map(DOM解析)


    package com.tencent.jungle.wechat.util;
    
    import com.google.inject.Singleton;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import java.io.StringReader;
    import java.util.HashMap;
    import java.util.Map;
    
    @Singleton
    public class XmlUtils {
        public static Document parseXmlString(String xmlStr){
    
            try{
                InputSource is = new InputSource(new StringReader(xmlStr));
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder=factory.newDocumentBuilder();
                Document doc = builder.parse(is);
                return doc;
            }catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }
    
        public static Map<String,Object> getXmlBodyContext(String bodyXml){
    
            Map<String,Object> dataMap = new HashMap<String,Object>();
    
            Document doc = parseXmlString(bodyXml);
            if(null != doc){
                NodeList rootNode = doc.getElementsByTagName("xml");
                if(rootNode != null){
    
                    Node root = rootNode.item(0);
                    NodeList nodes = root.getChildNodes();
                    for(int i = 0;i < nodes.getLength(); i++){
                        Node node = nodes.item(i);
                        dataMap.put(node.getNodeName(), node.getTextContent());
                    }
                }
            }
            return dataMap;
        }
    
    }
    
    
        public static void main(String[] args) {
            String xmlStr = "<xml><AppId></AppId><CreateTime>1413192605</CreateTime><InfoType></InfoType><ComponentVerifyTicket></ComponentVerifyTicket></xml>";
            Map<String, Object> map = XmlUtils.getXmlBodyContext(xmlStr);
            System.out.println(map);
        }
    
    
    
  • 相关阅读:
    根据snort规则写openvas nasl 攻击 脚本
    snort规则中tcp/udp端口的具体作用
    snort规则头解析
    正则匹配中的特殊案例
    snort 规则 byte_test 不同运算符命中条件
    Linux中tar命令的一些用法
    Thymeleaf传递url参数
    PO BO VO DTO POJO DAO DO 令人迷惑的Java概念
    linux中多个命令连接符— ; && || ()
    遇见了count(1)这种写法,什么意思?
  • 原文地址:https://www.cnblogs.com/QG-whz/p/10000239.html
Copyright © 2020-2023  润新知