Java tutorial
//package com.java2s; /* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Weave. If not, see <http://www.gnu.org/licenses/>. */ import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Node; public class Main { public static String getStringFromXML(Node node) throws TransformerException { return getStringFromXML(node, null); } public static String getStringFromXML(Node node, String dtdFilename) throws TransformerException { StringWriter sw = new StringWriter(); getStringFromXML(node, dtdFilename, sw); return sw.getBuffer().toString(); } public static void getStringFromXML(Node node, String dtdFilename, String outputFileName) throws TransformerException, IOException { File file = new File(outputFileName); if (!file.isFile()) file.createNewFile(); BufferedWriter out = new BufferedWriter(new FileWriter(file)); String workingPath = System.setProperty("user.dir", file.getAbsoluteFile().getParent()); try { getStringFromXML(node, dtdFilename, out); } finally { System.setProperty("user.dir", workingPath); } out.flush(); out.close(); } public static void getStringFromXML(Node node, String dtdFilename, Writer outputWriter) throws TransformerException { File dtdFile = null; String workingPath = null; if (dtdFilename != null) { dtdFile = new File(dtdFilename); workingPath = System.setProperty("user.dir", dtdFile.getAbsoluteFile().getParent()); } try { if (node instanceof Document) node = ((Document) node).getDocumentElement(); TransformerFactory tranFact = TransformerFactory.newInstance(); Transformer tf = tranFact.newTransformer(); if (dtdFile != null) { tf.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dtdFile.getName()); tf.setOutputProperty(OutputKeys.INDENT, "yes"); } Source src = new DOMSource(node); Result dest = new StreamResult(outputWriter); tf.transform(src, dest); } finally { if (workingPath != null) System.setProperty("user.dir", workingPath); } } }