Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.util.Stack;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

public class Main {
    public static String getNodeHierarchy(Node node) {

        StringBuffer sb = new StringBuffer();
        if (node != null) {
            Stack<Node> st = new Stack<Node>();
            st.push(node);

            Node parent = node.getParentNode();

            while ((parent != null) && (parent.getNodeType() != Node.DOCUMENT_NODE)) {

                st.push(parent);

                parent = parent.getParentNode();
            }

            // constructs node hierarchy
            Node n = null;
            while (!st.isEmpty() && null != (n = st.pop())) {

                if (n instanceof Element) {
                    Element e = (Element) n;

                    if (sb.length() == 0) {
                        sb.append(e.getTagName());
                    } else {
                        sb.append("/" + e.getTagName());
                    }
                }

            }
        }
        return sb.toString();

    }
}