scan XML Nodes - Java XML

Java examples for XML:XML Node Operation

Description

scan XML Nodes

Demo Code


//package com.java2s;

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

public class Main {
    public static void scanNodes(NodeList nodeList) throws Exception {
        scanNodes(nodeList, 1);/*from   w w  w. ja va2s . co  m*/
    }

    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;
        }
    }

    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;
    }
}

Related Tutorials