Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 Copyright 2014 Michael K Martin
    
 This file is part of Civet.
    
 Civet is free software: you can redistribute it and/or modify
 it under the terms of the Lesser GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
    
 Civet is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
    
 You should have received a copy of the Lesser GNU General Public License
 along with Civet.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.HashSet;
import java.util.Set;

import org.w3c.dom.Document;

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

public class Main {
    public static Set<String> getUniqueElementNames(Document dom) {
        HashSet<String> hNames = new HashSet<String>();
        Node docNode = dom.getDocumentElement();
        walkNodes(docNode, hNames);
        return hNames;
    }

    public static void walkNodes(Node nodeIn, StringBuffer sb, String sPad) {
        if (nodeIn == null)
            return;
        NamedNodeMap map = nodeIn.getAttributes();
        if (map != null)
            for (int i = 0; i < map.getLength(); i++) {
                Node n = map.item(i);
                if (n.getNodeType() == Node.ATTRIBUTE_NODE) {
                    sb.append(sPad + "   Attribute:" + n.getNodeName() + " = " + n.getNodeValue() + '\n');
                }
            }
        NodeList nodes = nodeIn.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                sb.append(sPad + "Element: " + n.getNodeName() + '\n');
            }
            if (n.getNodeType() == Node.TEXT_NODE) {
                sb.append(sPad + "   Value: = " + n.getNodeValue() + '\n');
            }
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                walkNodes(n, sb, sPad + "   ");
            }
        }
    }

    private static void walkNodes(Node nodeIn, HashSet<String> hElements) {
        if (nodeIn == null)
            return;
        NodeList nodes = nodeIn.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                String sNodeName = n.getNodeName();
                if (!hElements.contains(sNodeName))
                    hElements.add(sNodeName);
                walkNodes(n, hElements);
            }
        }
    }
}