Android XML NodeList to String Convert docToString(NodeList list)

Here you can find the source of docToString(NodeList list)

Description

doc To String

Declaration

private static String docToString(NodeList list) 

Method Source Code

//package com.java2s;

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

public class Main {
    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("\"");
                    }//from  w  ww.  ja va2 s  . c  o m
                }
                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();
    }
}