Java XML Node Print print(Node node)

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

Description

Prints the specified node, recursively.

License

Open Source License

Parameter

Parameter Description
node Node to be printed

Declaration

public static void print(Node node) 

Method Source Code

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

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.DocumentType;

public class Main {
    static java.io.PrintStream out = System.out;
    static boolean canonical = false;

    /** Prints the specified node, recursively.
     */*from   w ww  .  j a v a 2  s . c o m*/
     *  @param node Node to be printed
     */
    public static void print(Node node) {
        // is there anything to do?
        if (node == null) {
            return;
        }
        System.out.println("");

        int type = node.getNodeType();
        switch (type) {
        // print document
        case Node.DOCUMENT_NODE: {
            /*
            if (!canonical) {
              if (Encoding.equalsIgnoreCase("DEFAULT"))
            Encoding = "UTF-8";
              else if(Encoding.equalsIgnoreCase("Unicode"))
            Encoding = "UTF-16";
              else 
            Encoding = MIME2Java.reverse(Encoding);
            out.println("<?xml version=\"1.0\" encoding=\"" +
              Encoding + "\"?>");
            }
            */
            print(((Document) node).getDocumentElement());
            out.flush();
            break;
        }
        // print element with attributes
        case Node.ELEMENT_NODE: {
            out.print('<');
            out.print(node.getNodeName());
            Attr attrs[] = sortAttributes(node.getAttributes());
            for (int i = 0; i < attrs.length; i++) {
                Attr attr = attrs[i];
                out.print(' ');
                out.print(attr.getNodeName());
                out.print("=\"");
                out.print(normalize(attr.getNodeValue()));
                out.print('"');
            }
            out.print('>');
            NodeList children = node.getChildNodes();
            if (children != null) {
                int len = children.getLength();
                for (int i = 0; i < len; i++) {
                    print(children.item(i));
                }
            }
            break;
        }
        // handle entity reference nodes
        case Node.ENTITY_REFERENCE_NODE: {
            if (canonical) {
                NodeList children = node.getChildNodes();
                if (children != null) {
                    int len = children.getLength();
                    for (int i = 0; i < len; i++) {
                        print(children.item(i));
                    }
                }
            } else {
                out.print('&');
                out.print(node.getNodeName());
                out.print(';');
            }
            break;
        }
        // print cdata sections
        case Node.CDATA_SECTION_NODE: {
            if (canonical) {
                out.print(normalize(node.getNodeValue()));
            } else {
                out.print("<![CDATA[");
                out.print(node.getNodeValue());
                out.print("]]>");
            }
            break;
        }
        // print DocumentType sections
        case Node.DOCUMENT_TYPE_NODE: {
            out.print("<!DOCTYPE ");
            out.print(((DocumentType) node).getName());
            out.print(" SYSTEM ");
            out.print(((DocumentType) node).getSystemId());
            out.print(">");
            break;
        }
        // print text
        case Node.TEXT_NODE: {
            out.print(normalize(node.getNodeValue()));
            break;
        }
        // print processing instruction
        case Node.PROCESSING_INSTRUCTION_NODE: {
            out.print("<?");
            out.print(node.getNodeName());
            String data = node.getNodeValue();
            if (data != null && data.length() > 0) {
                out.print(' ');
                out.print(data);
            }
            out.print("?>");
            break;
        }
        }
        if (type == Node.ELEMENT_NODE) {
            out.print("</");
            out.print(node.getNodeName());
            out.print('>');
        }
        out.flush();
    }

    /** Returns a sorted list of attributes.
     *
     *  @param attrs A map of attributes
     *  @return A sorted array of attributes 
     */
    protected static Attr[] sortAttributes(NamedNodeMap attrs) {
        int len = (attrs != null) ? attrs.getLength() : 0;
        Attr array[] = new Attr[len];
        for (int i = 0; i < len; i++) {
            array[i] = (Attr) attrs.item(i);
        }
        /*    
        for (int i = 0; i < len - 1; i++) {
          String name  = array[i].getNodeName();
          int index = i;
          for (int j = i + 1; j < len; j++) {
        String curName = array[j].getNodeName();
        if (curName.compareTo(name) < 0) {
          name  = curName;
          index = j;
        }
          }
          if (index != i) {
        Attr temp    = array[i];
        array[i]     = array[index];
        array[index] = temp;
          }
        }
        */
        return (array);
    }

    /** Normalizes the given string.
     *
     *  @param The string to normalize
     *  @return The normalized string
     */
    public static String normalize(String s) {
        StringBuffer str = new StringBuffer();

        int len = (s != null) ? s.length() : 0;
        for (int i = 0; i < len; i++) {
            char ch = s.charAt(i);
            switch (ch) {
            case '<': {
                str.append("&lt;");
                break;
            }
            case '>': {
                str.append("&gt;");
                break;
            }
            case '&': {
                str.append("&amp;");
                break;
            }
            case '"': {
                str.append("&quot;");
                break;
            }
            case '\r':
            case '\n':
                // else, default append char
            default: {
                str.append(ch);
            }
            }
        }
        return str.toString();
    }
}

Related

  1. prettyPrint(Node root)
  2. prettyPrintLoop(Node node, StringBuilder string, String indentation)
  3. prettyPrintNode(Node aNode, int indent)
  4. print(Node node)
  5. printArrayContent(Node[] t)
  6. printDifferences(Node node1, Node node2)
  7. printDOM(Node node)
  8. printDOM(Node node, String prefix)