Java 怎么扫描XML节点

2019年8月3日23:49:13Java 怎么扫描XML节点已关闭评论 452 1233字阅读4分6秒

1.简介

Java 怎么扫描XML节点?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static void scanNode(Node node) throws Exception {
        int level = 1;
        String s = String.format("%" + level * 2 + "s", " ");
        scanNode(level, s, node);
    }

    private static int scanNode(int level, String s, Node node)
            throws Exception {
        String nodeName = node.getNodeName();
        String nodeValue = node.getNodeValue();
        System.out.println(s + nodeName + "    " + nodeValue);
        if (Node.ELEMENT_NODE == node.getNodeType()) {
            NamedNodeMap nodeMap = node.getAttributes();
            if (null != nodeMap) {
                for (int j = 0; j < nodeMap.getLength(); j++) {
                    String attributeName = nodeMap.item(j).getNodeName();
                    String attributeValue = nodeMap.item(j).getNodeValue();
                    System.out.println(s + "  " + attributeName + "    "
                            + attributeValue);
                }
            }
        }
        if (true == node.hasChildNodes()) {
            scanNodes(node.getChildNodes(), ++level);
        }
        return level;
    }

    public static void scanNodes(NodeList nodeList) throws Exception {
        scanNodes(nodeList, 1);
    }

    private static void scanNodes(NodeList nodeList, int level)
            throws Exception {
        String s = String.format("%" + level * 2 + "s", " ");
        try {
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                level = scanNode(level, s, node);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
}

 
继续阅读
编程十万个怎么办