JAVA 解析xml的工具类

package com.xml.util;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.xml.sax.InputSource;


/**
 * 解析xml的工具类 1、将多层级xml解析为Map 2、将多层级xml解析为Json
 * 
 * @author lmb
 * 
 */
public class ParseXmlUtil {
    public static Logger     logger     = Logger.getLogger(ParseXmlUtil.class);
    /**
     * 将xml格式响应报文解析为Json格式
     * 
     * @param responseXmlTemp
     * @return
     * @throws IOException 
     * @throws JDOMException 
     * @throws DocumentException
     */
    public static String xml2Json(String responseXmlTemp, JSONObject node, String currentNode, String listcurrentNode) throws JDOMException, IOException
         {
        
        InputSource source = new InputSource(new StringReader(responseXmlTemp.trim()));
        SAXBuilder builder = new SAXBuilder();
        Document doc = null;
            doc = builder.build(source);
        Element rootElement = doc.getRootElement();
        Map<String, Object> mapXml = new TreeMap<String, Object>();
        element2Map(mapXml, rootElement, node, currentNode, listcurrentNode);
        String jsonXml = JSONObject.fromObject(mapXml).toString();
        System.out.println("Json >>> " + jsonXml);
        return jsonXml;
    }

    /**
     * 将xml格式响应报文解析为Json格式
     * 
     * @param responseXmlTemp
     * @return
     * @throws IOException 
     * @throws JDOMException 
     */
    public static String xml2Json(String responseXmlTemp) throws JDOMException, IOException {
        Document doc = null;
        InputSource source = new InputSource(new StringReader(responseXmlTemp.trim()));
        SAXBuilder builder = new SAXBuilder();
            doc = builder.build(source);
        Element rootElement = doc.getRootElement();
        Map<String, Object> mapXml = new TreeMap<String, Object>();
        element2Map(mapXml, rootElement);
        String jsonXml = JSONObject.fromObject(mapXml).toString();
        System.out.println("Json >>> " + jsonXml);
        return jsonXml;
    }

    /**
     * 将xml格式响应报文解析为Map格式
     * 
     * @param responseXmlTemp
     * @param thirdXmlServiceBean
     * @return
     * @throws IOException 
     * @throws JDOMException 
     * @throws DocumentException
     */
    public static Map<String, Object> xml2map(String responseXmlTemp, JSONObject node, String currentNode,
        String listCurrentNode) throws JDOMException, IOException {
        Document doc = null;
        InputSource source = new InputSource(new StringReader(responseXmlTemp.trim()));
        SAXBuilder builder = new SAXBuilder();
            doc = builder.build(source);
        Element rootElement = doc.getRootElement();
        Map<String, Object> mapXml = new TreeMap<String, Object>();
        element2Map(mapXml, rootElement, node, currentNode, listCurrentNode);
        return mapXml;
    }

    public static Map<String, Object> xml2map(String responseXmlTemp) throws JDOMException, IOException {
        Document doc = null;
        InputSource source = new InputSource(new StringReader(responseXmlTemp.trim()));
        SAXBuilder builder = new SAXBuilder();
            doc = builder.build(source);
        Element rootElement = doc.getRootElement();
        Map<String, Object> mapXml = new TreeMap<String, Object>();
        element2Map(mapXml, rootElement);
        return mapXml;
    }

    /**
     * 使用递归调用将多层级xml转为map
     * 
     * @param map
     * @param rootElement
     */
    @SuppressWarnings( {"unchecked", "rawtypes"})
    public static void element2Map(Map<String, Object> map, Element rootElement, JSONObject node, String currentNode,
        String listcurrentNode) {
        // 获得当前节点的子节点
        List<Element> elements = rootElement.getChildren();
        int elementsSize = elements.size();
        if (elementsSize == 0) {
            // 没有子节点说明当前节点是叶子节点,直接取值
            if (node.getJSONObject(currentNode) != null) {
                if (node.getJSONObject(currentNode).keySet().toString().contains(rootElement.getName())) {
                    map.put(rootElement.getName(), rootElement.getText());
                }
            }
        } else if (elementsSize == 1 && !elements.get(0).getName().equals(listcurrentNode) ) {
            // 只有一个子节点说明不用考虑list的情况,继续递归
            Map<String, Object> tempMap = new TreeMap<String, Object>();
            if (node.getJSONObject(currentNode) != null) {
                element2Map(tempMap, elements.get(0), node.getJSONObject(currentNode), elements.get(0).getName(),
                    listcurrentNode);
                if (node.getJSONObject(currentNode).keySet().contains(elements.get(0).getName())) {
                    map.put(elements.get(0).getName(), tempMap);
                }
            }

        } else {
            // 多个子节点的话就要考虑list的情况了,特别是当多个子节点有名称相同的字段时
            Map<String, Object> tempMap = new TreeMap<String, Object>();
            for (Element element : elements) {
                tempMap.put(element.getName(), null);
            }
            Set<String> keySet = tempMap.keySet();
            for (String string : keySet) {
                Namespace namespace = elements.get(0).getNamespace();
                List<Element> sameElements = rootElement.getChildren(string);
                // 如果同名的数目大于1则表示要构建list
                int sameElementSize = sameElements.size();
                if (sameElementSize > 1) {
                    List<Map> list = new ArrayList<Map>();
                    for (Element element : sameElements) {
                        Map<String, Object> sameTempMap = new TreeMap<String, Object>();
                        if (node.getJSONObject(currentNode).keySet().toString().contains(string)) {
                            if (node.getJSONObject(currentNode) != null) {
                                element2Map(sameTempMap, element, node.getJSONObject(currentNode), string,
                                    listcurrentNode);
                                list.add(sameTempMap);
                            }
                        }
                    }

                    if (node.getJSONObject(currentNode).keySet().toString().contains(string)) {
                        if (node.getJSONObject(currentNode) != null) {
                            map.put(string, list);
                        }
                    }
                } else {
                    // 同名的数量不大于1直接递归
                    if (listcurrentNode != null) {
                        String[] strarr = listcurrentNode.split(",");
                        for (int i = 0; i < strarr.length; i++) {
                            if (strarr[i].equals(string)) {
                                List<Map> list = new ArrayList<Map>();
                                for (Element element : sameElements) {
                                    Map<String, Object> sameTempMap = new TreeMap<String, Object>();
                                    if (node.getJSONObject(currentNode).keySet().toString().contains(string)) {
                                        if (node.getJSONObject(currentNode) != null) {
                                            element2Map(sameTempMap, element, node.getJSONObject(currentNode), string,
                                                listcurrentNode);
                                            list.add(sameTempMap);
                                        }
                                    }
                                }
                                if (node.getJSONObject(currentNode).keySet().toString().contains(string)) {
                                    if (node.getJSONObject(currentNode) != null) {
                                        map.put(string, list);
                                    }
                                }
                            } else {
                                Map<String, Object> sameTempMap = new TreeMap<String, Object>();
                                if (node.getJSONObject(currentNode).keySet().toString().contains(string)) {
                                    if (node.getJSONObject(currentNode) != null) {
                                        element2Map(sameTempMap, sameElements.get(0), node.getJSONObject(currentNode),
                                            string, listcurrentNode);
                                        map.put(string, sameTempMap);
                                    }
                                }
                            }
                        }
                    } else {
                        Map<String, Object> sameTempMap = new TreeMap<String, Object>();
                        if (node.getJSONObject(currentNode).keySet().toString().contains(string)) {
                            if (node.getJSONObject(currentNode) != null) {
                                element2Map(sameTempMap, sameElements.get(0), node.getJSONObject(currentNode), string,
                                    listcurrentNode);
                                map.put(string, sameTempMap);
                            }
                        }
                    }
                }

            }
        }
    }

    public static void element2Map(Map<String, Object> map, Element rootElement) {
        // 获得当前节点的子节点
        List<Element> elements = rootElement.getChildren();
        int elementsSize = elements.size();
        if (elementsSize == 0) {
            // 没有子节点说明当前节点是叶子节点,直接取值
            // if(node.getJSONObject(currentNode).keySet().toString().contains(rootElement.getName())) {
            map.put(rootElement.getName(), rootElement.getText());
            // }
        } else if (elementsSize == 1) {
            // 只有一个子节点说明不用考虑list的情况,继续递归
            Map<String, Object> tempMap = new TreeMap<String, Object>();
            element2Map(tempMap, elements.get(0));
            // if(node.getJSONObject(currentNode).keySet().contains(elements.get(0).getName())) {
            map.put(elements.get(0).getName(), tempMap);
            // }
        } else {
            // 多个子节点的话就要考虑list的情况了,特别是当多个子节点有名称相同的字段时
            Map<String, Object> tempMap = new TreeMap<String, Object>();
            for (Element element : elements) {
                tempMap.put(element.getName(), null);

            }
            Set<String> keySet = tempMap.keySet();
            for (String string : keySet) {
                Namespace namespace = elements.get(0).getNamespace();
                List<Element> sameElements = rootElement.getChildren(string);
                // 如果同名的数目大于1则表示要构建list
                int sameElementSize = sameElements.size();
                if (sameElementSize > 1) {
                    List<Map> list = new ArrayList<Map>();
                    for (Element element : sameElements) {
                        Map<String, Object> sameTempMap = new TreeMap<String, Object>();
                        element2Map(sameTempMap, element);
                        list.add(sameTempMap);
                    }
                    map.put(string, list);
                } else {
                    // 同名的数量不大于1直接递归
                    Map<String, Object> sameTempMap = new TreeMap<String, Object>();
                    element2Map(sameTempMap, sameElements.get(0));
                    map.put(string, sameTempMap);
                }
            }
        }

    }

    @SuppressWarnings("unchecked")
    public static void parseData(Map<?, ?> map,JSONObject jsonObject) {
        if (map.size() == 1) {
            for (Object key : map.keySet()) {
                Object value = map.get(key);
                if (value.toString().startsWith("[") && value.toString().endsWith("]")) {
                    jsonObject.put(key, value);
                    // List<?> list = (List<?>)value;
                    // Iterator<?> iterator = list.iterator();
                    // while(iterator.hasNext()){
                    // value = iterator.next();
                    // parseData((Map<String, Object>)value);
                    // }
                    // System.out.println(key+"  "+value);
                } else if (!value.toString().startsWith("{") && !value.toString().endsWith("}")) {
                    if (jsonObject.get(key) != null) {
                        if (!jsonObject.get(key).toString().startsWith("[")
                            && !jsonObject.get(key).toString().endsWith("]")) {
                            jsonObject.put(key, "" + jsonObject.getString((String)key).toString() + "|"
                                + (value).toString() + "");
                        } else {
                            jsonObject.put(key, "\"" + jsonObject.getJSONArray((String)key).toString() + "|"
                                + JSONArray.fromObject(value).toString() + "\"");
                        }
                    } else {
                        jsonObject.put(key, value);
                    }
                } else {
                    parseData((Map<String, Object>)value,jsonObject);
                }
            }
        } else {
            for (Object key : map.keySet()) {
                Object value = map.get(key); 
                    if (value.toString().startsWith("[") && value.toString().endsWith("]")) {
               
                        // List<?> list = (List<?>)value;
                        // for(int i = 0;i < list.size();i++)
                        // {
                        // Map<String,Object> map1 = (Map<String, Object>) list.get(i);
                        // parseData(map1);
                        // }
                        if (jsonObject.get(key) != null) {
                            jsonObject.put(key, "\"" + jsonObject.getJSONArray((String)key).toString() + "|"
                                + JSONArray.fromObject(value).toString() + "\"");
                        } else {
                            jsonObject.put(key, value);
                        }
                    } else {
                        if (value.toString().startsWith("{") && value.toString().endsWith("}")) {
                        parseData((Map<String, Object>)value,jsonObject);
                        }
                    }
                }
            }
        }
    }

 // 获取一个xml文件
                            String textFromFile = MyXmlUtil.XmlToString("");

//currentNode    XML最大的那个key                               

//listcurrentNode  在xml中多个循环的数据

//两个相同的XML key值得value 会按|分割最里面数据得在最第一个,按此规则排列排列1|1|1|1

//调用 将xml解析为Map
                            Map<String, Object> resultMap =
                                ParseXmlUtil.xml2map(textFromFile, nodejson, currentNode, listcurrentNode);

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * 本类是专门解析XML文件的,主要用于为系统读取自己的配置文件时提供最方便的解析操作 * @author HX * */ public class XmlManager { /** * 得到某节点下某个属性的值 * @param element 要获取属性的节点 * @param attributeName 要取值的属性名称 * @return 要获取的属性的值 * @author HX_2010-01-12 */ public static String getAttribute( Element element, String attributeName ) { return element.getAttribute( attributeName ); } /** * 获取指定节点下的文本 * @param element 要获取文本的节点 * @return 指定节点下的文本 * @author HX_2010-01-12 */ public static String getText( Element element ) { return element.getFirstChild().getNodeValue(); } /** * 解析某个xml文件,并在内存中创建DOM树 * @param xmlFile 要解析XML文件 * @return 解析某个配置文件后的Document * @throws Exception xml文件不存在 */ public static Document parse( String xmlFile ) throws Exception { // 绑定XML文件,建造DOM树 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document domTree = db.parse( xmlFile ); return domTree; } /** * 获得某节点下的某个子节点(指定子节点名称,和某个属性的值) * 即获取parentElement下名字叫childName,并且属性attributeName的值为attributeValue的子结点 * @param parentElement 要获取子节点的那个父节点 * @param childName 要获取的子节点名称 * @param attributeName 要指定的属性名称 * @param attributeValue 要指定的属性的值 * @return 符合条件的子节点 * @throws Exception 子结点不存在或有多个符合条件的子节点 * @author HX_2008-12-01 */ public static Element getChildElement( Element parentElement, String childName, String attributeName, String attributeValue ) throws Exception { NodeList list = parentElement.getElementsByTagName( childName ); int count = 0; Element curElement = null; for ( int i = 0 ; i < list.getLength() ; i ++ ) { Element child = ( Element )list.item( i ); String value = child.getAttribute( attributeName ); if ( true == value.equals( attributeValue ) ) { curElement =

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值