Java XML Node to String toString(Node n)

Here you can find the source of toString(Node n)

Description

to String

License

Apache License

Declaration

public static String toString(Node n) 

Method Source Code

//package com.java2s;
/**// w  ww. j ava  2s  .  c o  m
*      Copyright (C) 2008 10gen Inc.
*  
*    Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*  
*       http://www.apache.org/licenses/LICENSE-2.0
*  
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*/

import org.w3c.dom.*;

public class Main {
    public static String toString(Node n) {
        StringBuilder buf = new StringBuilder();
        append(n, buf, 0);
        return buf.toString();
    }

    public static StringBuilder append(Node n, StringBuilder buf, int level) {
        if (n instanceof CharacterData)
            return _level(buf, level).append(n.getNodeValue()).append("\n");

        _level(buf, level).append("<").append(n.getNodeName());
        NamedNodeMap attr = n.getAttributes();
        if (attr != null) {
            for (int i = 0; i < attr.getLength(); i++) {
                Node a = attr.item(i);
                buf.append(" ").append(a.getNodeName()).append("=\"").append(a.getNodeValue()).append("\" ");
            }
        }

        NodeList children = n.getChildNodes();
        if (children == null || children.getLength() == 0)
            return buf.append("/>\n");
        buf.append(">\n");

        for (int i = 0; i < children.getLength(); i++) {
            Node c = children.item(i);
            append(c, buf, level + 1);
        }

        return _level(buf, level).append("</").append(n.getNodeName()).append(">\n");
    }

    static StringBuilder _level(StringBuilder buf, int level) {
        for (int i = 0; i < level; i++)
            buf.append(" ");
        return buf;
    }
}

Related

  1. toString(final Node node)
  2. toString(final Node node)
  3. toString(final Node xml)
  4. toString(final short nodeType)
  5. toString(Node element)
  6. toString(Node n)
  7. toString(Node node)
  8. toString(Node node)
  9. toString(Node node)