/* * (C) Copyright IBM Corp. 2004. All rights reserved. * * US Government Users Restricted Rights Use, duplication or * disclosure restricted by GSA ADP Schedule Contract with IBM Corp. * * The program is provided "as is" without any warranty express or * implied, including the warranty of non-infringement and the implied * warranties of merchantibility and fitness for a particular purpose. * IBM will not be liable for any damages suffered by you as a result * of using the Program. In no event will IBM be liable for any * special, indirect or consequential damages or lost profits even if * IBM has been advised of the possibility of their occurrence. IBM * will not be liable for any third party claims against you. */ package com.ibm.dw.xmlprogjava; //import javax.xml.parsers.DocumentBuilder; //import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * A DOM traversal program. Given a DOM Node, the one static method * of this program prints the contents of the Node as XML. */ public class DomTreePrinter { /** Prints the specified node, recursively. */ public static void printNode(Node node) { int type = node.getNodeType(); switch (type) { // print the document element case Node.DOCUMENT_NODE: { System.out.println(""); printNode(((Document)node).getDocumentElement()); break; } // print element and any attributes case Node.ELEMENT_NODE: { System.out.print("<"); System.out.print(node.getNodeName()); if (node.hasAttributes()) { NamedNodeMap attrs = node.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) printNode(attrs.item(i)); } System.out.print(">"); if (node.hasChildNodes()) { NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) printNode(children.item(i)); } break; } // Print attribute nodes case Node.ATTRIBUTE_NODE: { System.out.print(" " + node.getNodeName() + "=\""); if (node.hasChildNodes()) { NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) printNode(children.item(i)); } System.out.print("\""); break; } // handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { System.out.print("&"); System.out.print(node.getNodeName()); 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()); break; } case Node.COMMENT_NODE: { System.out.print(""); break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { System.out.print(""); break; } } if (type == Node.ELEMENT_NODE) { System.out.print("'); } } // printNode(Node) }