get Xml String from DOM Node - Java XML

Java examples for XML:DOM Node Value

Description

get Xml String from DOM Node

Demo Code


//package com.java2s;

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

public class Main {
    public final static String getXml(Node node) {
        // http://groups.google.com/group/android-developers/browse_thread/thread/2cc84c1bc8a6b477/5edb01c0721081b0
        StringBuilder buffer = new StringBuilder();

        if (node == null) {
            return "";
        }//from   w w w.j a v  a2  s  .  c  o m

        if (node instanceof Document) {
            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            buffer.append(getXml(((Document) node).getDocumentElement()));
        } else if (node instanceof Element) {
            Element element = (Element) node;
            buffer.append("<");
            buffer.append(element.getNodeName());
            if (element.hasAttributes()) {
                NamedNodeMap map = element.getAttributes();
                for (int i = 0; i < map.getLength(); i++) {
                    Node attr = map.item(i);
                    buffer.append(" ");
                    buffer.append(attr.getNodeName());
                    buffer.append("=\"");
                    buffer.append(attr.getNodeValue());
                    buffer.append("\"");
                }
            }
            buffer.append(">");
            NodeList children = element.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                buffer.append(getXml(children.item(i)));
            }
            buffer.append("</");
            buffer.append(element.getNodeName());
            buffer.append(">\n");
        } else if (node != null && node.getNodeValue() != null) {
            buffer.append(node.getNodeValue());
        }

        return buffer.toString();
    }
}

Related Tutorials