Prints a textual representation of the given XML node to the specified PrintStream. - Java XML

Java examples for XML:DOM Node

Description

Prints a textual representation of the given XML node to the specified PrintStream.

Demo Code


//package com.java2s;
import java.io.PrintStream;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.Text;

public class Main {
    /**//from  w  ww  . ja  v a 2 s . c om
     * Prints a textual representation of the given node to the specified PrintStream.
     *
     * @param  n    Node that is to be printed.
     * @param  out  The PrintStream to which the node is to be printed.
     * @pre    n != null && out != null
     */
    public static void printXMLNode(Node n, PrintStream out) {
        switch (n.getNodeType()) {
        case Node.DOCUMENT_NODE:
            out.println("DOC_ROOT");
            break;

        case Node.ELEMENT_NODE:
            out.println("<" + ((Element) n).getTagName() + ">");
            break;

        case Node.ATTRIBUTE_NODE:
            out.println("@" + ((Attr) n).getName());
            break;

        case Node.TEXT_NODE:
            out.println("\"" + ((Text) n).getWholeText().trim() + "\"");
            break;

        case Node.COMMENT_NODE:
            out.println("COMMENT: \"" + n.getTextContent().trim() + "\"");
            break;

        default:
            out.println("Unknown node type: " + n.getNodeType());
        }
    }
}

Related Tutorials