报文XML格式转JSONObject或者Map的工具类

遇到解析xml的问题,从网上扒了各种工具,总结一下几个好用的。希望对大家也有用!


需要解析的xml:
String xmlString ="800218153612918002345ad652d1d21e2907be9e2fa3f70c112";

方法一返回Object:
  /*循环解析XML将数据以json对象的形式返回*/
    public static com.alibaba.fastjson.JSONObject xmlToJson(String xmlString){
        Document doc = null;
        com.alibaba.fastjson.JSONObject jsob=new com.alibaba.fastjson.JSONObject();
        try{
            doc = DocumentHelper.parseText(xmlString);
            Element empRoot =doc.getRootElement();
            if(empRoot.attributeCount()>0){
                for(int i=0;i

方法二返回Map:

/**
     * xml转map 带属性
     * @param xmlStr xmlStr
     * @param needRootKey 是否需要在返回的map里加根节点键
     * @return map
     */
    public static Map xmlToMap(String xmlString, boolean needRootKey)     {
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xmlString);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = doc.getRootElement();
        Map map = xml2mapWithAttr(root);
        if(root.elements().size()==0 && root.attributes().size()==0){
            // 根节点只有一个文本内容
            return map;
        }
        if(needRootKey){
            // 在返回的map里加根节点键(如果需要)
            Map rootMap = new HashMap();
            rootMap.put(root.getName(), map);
            return rootMap;
        }
        return map;
    }

第一种输出:

{
    "body": "", 
    "ctrl": "", 
    "id": "1536129180023", 
    "key": "45ad652d1d21e2907be9e2fa3f70c112", 
    "loto": "", 
    "orderno": "880324324566733", 
    "time": "1536129190023", 
    "timestamp": "1536129180023", 
    "userId": "800218", 
    "v": "1.0"
}

第二种输出:

{msg={@v=1.0, @id=1536129180023, ctrl={userId=800218, time=1536129190023, timestamp=1536129180023, key=45ad652d1d21e2907be9e2fa3f70c112}, body={loto={@orderno=880324324566733, #text=}}}}

你可能感兴趣的:(技术分享)