Java XML Node Print printNode(Node node)

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

Description

Provides a representation of XML to stdout.

License

Open Source License

Parameter

Parameter Description
node It can be a document, an element, an entity, CDATA, text.

Declaration

public static void printNode(Node node) 

Method Source Code

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

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

public class Main {
    /**//from   ww w . j  a v a2  s  .  c  o  m
     * Provides a representation of XML to stdout.
     * 
     * @param node
     *            It can be a document, an element, an entity, CDATA, text.
     */
    public static void printNode(Node node) {
        int type = node.getNodeType();
        switch (type) {
        // print the document element
        case Node.DOCUMENT_NODE: {
            System.out.println("<?xml version=\"1.0\" ?>");
            printNode(((Document) node).getDocumentElement());
            break;
        }

        // print element with attributes
        case Node.ELEMENT_NODE: {
            System.out.print("<");
            System.out.print(node.getNodeName());
            NamedNodeMap attrs = node.getAttributes();
            for (int i = 0; i < attrs.getLength(); i++) {
                Node attr = attrs.item(i);
                System.out.print(" " + attr.getNodeName().trim() + "=\"" + attr.getNodeValue().trim() + "\"");
            }
            System.out.println(">");
            NodeList children = node.getChildNodes();
            if (children != null) {
                for (int i = 0; i < children.getLength(); i++) {
                    printNode(children.item(i));
                }

            }
            break;
        }

        // handle entity reference nodes
        case Node.ENTITY_REFERENCE_NODE: {
            System.out.print("&");
            System.out.print(node.getNodeName().trim());
            System.out.print(";");
            break;
        }

        // print cdata sections
        case Node.CDATA_SECTION_NODE: {
            System.out.print("");
            break;
        }

        // print text
        case Node.TEXT_NODE: {
            System.out.print(node.getNodeValue().trim());
            break;
        }

        // print processing instruction
        case Node.PROCESSING_INSTRUCTION_NODE: {
            System.out.print("");
            break;
        }

        }

        if (type == Node.ELEMENT_NODE) {
            System.out.println();
            System.out.print("");
        }
    }
}

Related

  1. printElement(Node node, int level)
  2. printlnCommon(Node n)
  3. printNode(final String indent, final Node node)
  4. printNode(Node aNode, int aLevel)
  5. printNode(Node node)
  6. printNode(Node node)
  7. printNode(Node node)
  8. printNode(Node node, int level)
  9. printNode(Node node, PrintStream out)