Java XML Node to String toString(Node node)

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

Description

to String

License

Open Source License

Parameter

Parameter Description
node a parameter

Declaration

public static String toString(Node node) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;
import java.util.List;

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

public class Main {
    /**//  ww  w  .j ava 2s.  com
     * 
     * @param node
     * @return
     * @deprecated Use {@link #getXmlAsString(Node)} instead.
     */
    public static String toString(Node node) {
        StringBuffer sb = new StringBuffer();
        if (node instanceof Text) {
            if (node.getNodeValue() != null) {
                byte[] bytes = node.getNodeValue().getBytes();
                List<Byte> newBytes = new ArrayList<Byte>();
                for (int i = 0; i < bytes.length; i++) {
                    if (bytes[i] == 63) {
                        byte[] bs = "&nbsp;".getBytes();
                        for (byte b : bs) {
                            newBytes.add(b);
                        }
                    } else {
                        newBytes.add(bytes[i]);
                    }
                }
                byte[] valueBytes = new byte[newBytes.size()];
                for (int i = 0; i < newBytes.size(); i++) {
                    valueBytes[i] = newBytes.get(i).byteValue();
                }
                sb.append(new String(valueBytes));
            }
        } else {
            sb.append("<").append(node.getNodeName());
            NamedNodeMap attrs = node.getAttributes();
            for (int j = 0; j < attrs.getLength(); j++) {
                sb.append(" ").append(attrs.item(j).getNodeName()).append("=\"")
                        .append(attrs.item(j).getNodeValue()).append("\"");
            }
            sb.append(">");
            if (node.hasChildNodes()) {
                NodeList children = node.getChildNodes();
                for (int i = 0; i < children.getLength(); i++) {
                    String str = toString(children.item(i));
                    if (str != null)
                        sb.append(str);
                }
            } else {
                sb.append(node.getNodeValue());
            }
            sb.append("</").append(node.getNodeName()).append(">");
        }
        return sb.toString();
    }
}

Related

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