get All XML Children - Java XML

Java examples for XML:XML Element Child

Description

get All XML Children

Demo Code


//package com.java2s;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class Main {
    private static String HTMLString = "";

    public static int getAllChildren(Node start, int offset) {
        //String spacers  = "                                                         ";
        String tagOpen = "<";
        String tagClose = ">";
        String tagEndOpen = "</";
        String tagEndClose = ">";
        String tagName = start.getNodeName();
        String tagValue = (start.getNodeValue() == null ? "" : start
                .getNodeValue());// w  w w.ja va2s .c o  m

        if (start.getNodeName().trim().equals("#text")) {
            tagOpen = "";
            tagClose = "";
            tagName = "";
            tagEndOpen = "";
            tagEndClose = "";
        } else if (start.getNodeName().trim().equals("#comment")) {
            tagOpen = "<!--";
            tagClose = "";
            tagName = "";
            tagEndOpen = "";
            tagEndClose = "-->";
        }
        if (offset == 0)
            HTMLString = "";

        HTMLString += tagOpen + tagName;

        if (start.getNodeType() == Element.ELEMENT_NODE) {
            NamedNodeMap startAttr = start.getAttributes();
            for (int i = 0; i < startAttr.getLength(); i++) {
                Node attr = startAttr.item(i);
                HTMLString += " " + attr.getNodeName() + "=\""
                        + attr.getNodeValue() + "\"";
            }
        }
        HTMLString += tagClose + tagValue;

        for (Node child = start.getFirstChild(); child != null; child = child
                .getNextSibling()) {
            getAllChildren(child, offset + 1);
        }

        //if (offset > 0 && tagName.length() > 0) {
        if (tagName.length() > 0
                || start.getNodeName().trim().equals("#comment")) {
            HTMLString += tagEndOpen + tagName + tagEndClose;
        }

        return ++offset;
    }
}

Related Tutorials