Java tutorial
//package com.java2s; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** Prints the specified node, then prints all of its children. */ public static void printDOM(Node node) { int type = node.getNodeType(); switch (type) { // print the document element case Node.DOCUMENT_NODE: { System.out.print("<?xml version=\"1.0\" ?>"); printDOM(((Document) node).getDocumentElement()); break; } // print element with attributes case Node.ELEMENT_NODE: { System.out.println(); 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.print(">"); NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) printDOM(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("<![CDATA["); System.out.print(node.getNodeValue().trim()); System.out.print("]]>"); break; } // print text case Node.TEXT_NODE: { System.out.println(); System.out.print(node.getNodeValue().trim()); break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { System.out.print("<?"); System.out.print(node.getNodeName().trim()); String data = node.getNodeValue().trim(); { System.out.print(" "); System.out.print(data); } System.out.print("?>"); break; } } if (type == Node.ELEMENT_NODE) { System.out.println(); System.out.print("</"); System.out.print(node.getNodeName().trim()); System.out.print('>'); } } }