Java tutorial
//package com.java2s; /* // Licensed to Julian Hyde under one or more contributor license // agreements. See the NOTICE file distributed with this work for // additional information regarding copyright ownership. // // Julian Hyde 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.*; public class Main { private static void prettyPrintLoop(NodeList nodes, StringBuilder string, String indentation) { for (int index = 0; index < nodes.getLength(); index++) { prettyPrintLoop(nodes.item(index), string, indentation); } } private static void prettyPrintLoop(Node node, StringBuilder string, String indentation) { if (node == null) { return; } int type = node.getNodeType(); switch (type) { case Node.DOCUMENT_NODE: string.append("\n"); prettyPrintLoop(node.getChildNodes(), string, indentation + "\t"); break; case Node.ELEMENT_NODE: string.append(indentation); string.append("<"); string.append(node.getNodeName()); Attr[] attributes; if (node.getAttributes() != null) { int length = node.getAttributes().getLength(); attributes = new Attr[length]; for (int loopIndex = 0; loopIndex < length; loopIndex++) { attributes[loopIndex] = (Attr) node.getAttributes().item(loopIndex); } } else { attributes = new Attr[0]; } for (Attr attribute : attributes) { string.append(" "); string.append(attribute.getNodeName()); string.append("=\""); string.append(attribute.getNodeValue()); string.append("\""); } string.append(">\n"); prettyPrintLoop(node.getChildNodes(), string, indentation + "\t"); string.append(indentation); string.append("</"); string.append(node.getNodeName()); string.append(">\n"); break; case Node.TEXT_NODE: string.append(indentation); string.append(node.getNodeValue().trim()); string.append("\n"); break; case Node.PROCESSING_INSTRUCTION_NODE: string.append(indentation); string.append("<?"); string.append(node.getNodeName()); String text = node.getNodeValue(); if (text != null && text.length() > 0) { string.append(text); } string.append("?>\n"); break; case Node.CDATA_SECTION_NODE: string.append(indentation); string.append("<![CDATA["); string.append(node.getNodeValue()); string.append("]]>"); break; } } }