Java 解析xml 使用SAXReader获取所有标签的key和value的代码实例

Java中使用SAXReader获取xml信息中所有标签的key和value,若是有二级或者继续嵌套,也可以递归获取的代码实例

/**
 * @author LiXuekai on 2020/7/26
 */
public class XmlTest2 {
    private static final String XML_INFO = "\n" +
            "\n" +
            "    20200715\n" +
            "    0\n" +
            "    " +
            "        100" +
            "        200" +
            "    \n" +
            "    N\n" +
            "    \n" +
            "    00000\n" +
            "    1001045\n" +
            "    \n" +
            "";

    @Test
    public void parse() throws DocumentException {
        SAXReader sr = new SAXReader();
        Document doc = sr.read(new ByteArrayInputStream(XML_INFO.getBytes(StandardCharsets.UTF_8)));
        Element root = doc.getRootElement();
        getChildNodes(root);
    }

    public static void getChildNodes(Element element) {
        Map map = Maps.newHashMap();
        String keyPrefix = "pre";
        forkv0(keyPrefix, map, element);
        //forkv1(element);
        //forkv2(element);
        out(map);
    }

    private static void out(Map map) {
        for (Map.Entry entry : map.entrySet()) {
            System.out.println(entry.getKey() + "  " + entry.getValue());
        }
    }

    private static void forkv0(String keyPrefix, Map map, Element element) {
        List elements = element.elements();
        for (Object o : elements) {
            try {
                Element e = (Element) o;
                String name = e.getName();
                Object data = e.getData();
                int size = e.elements().size();
                if (size > 0) {
                    String newKey = keyPrefix + "_" + name;
                    forkv0(newKey, map, e);
                } else {
                    map.put(keyPrefix + "_" + name, data);
                }
                //System.out.println("key is " + name + " ; value is " + data + " ; size is " + size);
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }
    }

    private static void forkv2(Element element) {
        System.out.println(element.getName());
        Iterator it = element.nodeIterator();
        while (it.hasNext()) {
            Node node = it.next();
            //只有标签节点才有子节点 所以判断这个节点是否是标签节点
            if (node instanceof Element) {
                Element element1 = (Element) node;
                forkv2(element1);
            }
        }
    }

    private static void forkv1(Element element) {
        Iterator iterator = element.elementIterator();
        while (iterator.hasNext()) {
            Element next = (Element) iterator.next();
            Object data = next.getData();
            System.out.println(next.getName() + "  " + data);
        }
    }
}

运行结果截图

Java 解析xml 使用SAXReader获取所有标签的key和value的代码实例_第1张图片

 

你可能感兴趣的:(java,xml,java)