Android XML Document to String Convert xmlDocumentToString(Document document)

Here you can find the source of xmlDocumentToString(Document document)

Description

xml Document To String

Declaration

public static final String xmlDocumentToString(Document document) 

Method Source Code

//package com.java2s;

import org.w3c.dom.Document;

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

public class Main {
    public static final String xmlDocumentToString(Document document) {
        // borrowed and modified from
        // http://wurstgranulat.de/projekte/java-library-android-xml-document-string/
        return docToString(document.getChildNodes()).trim();
    }/*  ww  w.  j  a v  a2  s .  c o  m*/

    private static String docToString(NodeList list) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < list.getLength(); i++) {
            Node item = list.item(i);

            if (item.getNodeType() == Node.TEXT_NODE) {
                builder.append(item.getNodeValue());
            } else {
                builder.append("\n<").append(item.getNodeName());
                NamedNodeMap attributes = item.getAttributes();
                if (attributes != null) {
                    int max = attributes.getLength();
                    for (int j = 0; j < max; j++) {
                        Node attribute = attributes.item(j);
                        builder.append(" ").append(attribute.getNodeName())
                                .append("=\"")
                                .append(attribute.getNodeValue())
                                .append("\"");
                    }
                }
                builder.append(">");
            }
            if (item.getChildNodes().getLength() > 0) {
                builder.append(docToString(item.getChildNodes()));
            }
            if (item.getNodeType() != Node.TEXT_NODE) {
                if (builder.charAt(builder.length() - 1) == '>') {
                    builder.append("\n");
                }
                builder.append("</").append(item.getNodeName()).append(">")
                        .toString();
            }
        }
        return builder.toString();
    }
}

Related

  1. toXML(Document document)
  2. getXml(Document doc)
  3. numResults(Document doc)
  4. documentToString(Node n)
  5. getErrorText(Document xml)
  6. xmlToString(Document doc)