Java tutorial
//package com.java2s; import org.w3c.dom.*; import java.io.*; public class Main { public static void writeXML(Document d, OutputStream os, String sysID) throws IOException { /** * To support i18n, we have to specify the encoding of * output writer to UTF-8 when we writing the XML. */ // PrintWriter out=new PrintWriter(os); PrintWriter out = new PrintWriter(new OutputStreamWriter(os, "UTF-8")); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println(); if (sysID != null) { out.println("<!DOCTYPE " + d.getDoctype().getName() + " SYSTEM \"" + sysID + "\">"); out.println(); } //d.getDocumentElement().normalize(); writeXMLwalkTree(d.getDocumentElement(), 0, out); out.flush(); } protected static void writeXMLwalkTree(Node node, int indent, PrintWriter out) { if (node == null) throw new NullPointerException("Null node passed to writeXMLwalkTree()"); if (node.hasChildNodes()) { if (node instanceof Element) { Element elem = (Element) node; //elem.normalize(); out.print("\n"); for (int j = 0; j < indent; j++) { out.print(" "); } out.print("<" + elem.getTagName()); NamedNodeMap attrs = elem.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Attr a = (Attr) attrs.item(i); out.print(" " + a.getName() + "=\"" + a.getValue() + "\""); } out.print(">"); NodeList nl = node.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { writeXMLwalkTree(nl.item(i), indent + 2, out); } // for(int j=0;j<indent;j++) { // out.print(" "); // } out.println("</" + elem.getTagName() + ">"); } } else { if (node instanceof Element) { Element elem = (Element) node; out.print("\n"); for (int j = 0; j < indent; j++) { out.print(" "); } out.print("<" + elem.getTagName()); NamedNodeMap attrs = elem.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Attr a = (Attr) attrs.item(i); out.print(" " + a.getName() + "=\"" + a.getValue() + "\""); } out.println("/>"); } else if (node instanceof CDATASection) { CDATASection cdata = (CDATASection) node; // for(int j=0;j<indent;j++) { // out.print(" "); // } out.print("<![CDATA[" + cdata.getData() + "]]>"); } else if (node instanceof Text) { Text text = (Text) node; StringBuilder buf = new StringBuilder(text.getData().length()); for (int i = 0; i < text.getData().length(); i++) { if (text.getData().charAt(i) == '\n' || text.getData().charAt(i) == '\r' || text.getData().charAt(i) == ' ' || text.getData().charAt(i) == '\t') { if (buf.length() > 0 && buf.charAt(buf.length() - 1) != ' ') { buf.append(' '); } } else { buf.append(text.getData().charAt(i)); } } if (buf.length() > 0 && !buf.toString().equals(" ")) { StringBuilder buf2 = new StringBuilder(buf.length() + indent); // for(int j=0;j<indent;j++) { // buf2.append(' '); // } buf2.append(buf.toString()); out.print(buf2); } } } } }