java dom4j 遍历xml字符串中所有元素和属性的值

项目中需要接受返回的xml的字符串报文,需要提取响应的值,于是有了以下代码。
dom4j jar包下载地址:https://dom4j.github.io

public class XMLTest {

    public static void main(String[] args) {
        String xml = "\n" +
                "" +
                "   " +
                "       " +
                "   " +
                "";

        Map> map = getElementMap(xml);
        for(Map.Entry> entry : map.entrySet()) {
            System.out.println("-------" + entry.getKey());
            for(Map.Entry entry1 : entry.getValue().entrySet()) {
                System.out.println(entry1.getKey() + "               " + entry1.getValue());
            }
        }
    }

    public static Map> getElementMap(String xml) {
        Map> map = new HashMap>();
        try {
            Document document = DocumentHelper.parseText(xml);
            Element rootElement = document.getRootElement();
            recursionElements(map, rootElement);

        } catch (DocumentException e) {
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 递归遍历所有Element,将其本身的值和属性的值放入map中,每个节点的值可用其名获取
     * @param map
     * @param parentElement
     */
    public static void recursionElements(Map> map, Element parentElement) {
        System.out.println("******" + parentElement.getName());

        //将父节点本身的信息存入map中
        Map parentMap = new HashMap();
        parentMap.put(parentElement.getName(), parentElement.getText());

        List attributes = parentElement.attributes();
        if(attributes != null && attributes.size() > 0) {
            for(Attribute attribute : attributes) {
                parentMap.put(attribute.getName(), attribute.getValue());
            }
        }
        map.put(parentElement.getName(), parentMap);

        //将其子节点的信息存入map中
        List childList = null;
        for(Element element : parentElement.elements()) {
            childList = element.elements();
            //当其没有子节点时,将其信息放入map中
            if(childList == null || childList.size() == 0) {
                List attributeList = element.attributes();
                Map childMap = new HashMap();
                childMap.put(element.getName(), element.getText());
                if(attributeList != null && attributeList.size() > 0) {
                    for(Attribute attribute : attributeList) {
                        childMap.put(attribute.getName(), attribute.getValue());
                    }
                }
                map.put(element.getName(), childMap);
            } else {
                //当其存在子节点时,递归遍历
                recursionElements(map, element);
            }
        }
    }

}

你可能感兴趣的:(Java)