Convert XML DOM document To String - Java XML

Java examples for XML:DOM

Description

Convert XML DOM document To String

Demo Code


//package com.java2s;

import org.w3c.dom.*;

public class Main {
    public static String documentToString(Node n) {
        StringBuilder buffer = new StringBuilder();
        if (n == null)
            return "";
        if (n instanceof Document) {
            buffer.append(documentToString((n).getFirstChild()));
        } else if (n instanceof Element) {
            Element element = (Element) n;
            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("\"");
                }// ww  w .jav  a2  s  .  c  o  m
            }
            buffer.append(">");
            NodeList children = element.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                buffer.append(documentToString(children.item(i)));
            }
            buffer.append("</");
            buffer.append(element.getNodeName());
            buffer.append(">");
        } else if (n != null && n.getNodeValue() != null) {
            buffer.append(n.getNodeValue());
        }
        return buffer.toString();
    }
}

Related Tutorials