get All XML Children String - Java XML

Java examples for XML:XML Element Child

Description

get All XML Children String

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 getAllChildrenString(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.j  av  a2s  . c o m

        if (start.getNodeName().trim().equals("#text")) {
            tagOpen = "";
            tagClose = "";
            tagName = "";
            tagEndOpen = "";
            tagEndClose = "";
        }
        if (offset == 0)
            HTMLString = "";
        else {
            HTMLString += //spacers.substring(0, offset) +
            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()) {
            getAllChildrenString(child, offset + 1);
        }

        if (offset > 0 && tagName.length() > 0) {
            HTMLString += //spacers.substring(0, offset) +
            tagEndOpen + tagName + tagEndClose;
        }

        return ++offset;
    }
}

Related Tutorials