Here you can find the source of documentToString(Document doc)
Parameter | Description |
---|---|
doc | the document to transform. |
Parameter | Description |
---|---|
TransformerException | if the transformation failed. |
public static String documentToString(Document doc) throws TransformerException
//package com.java2s; /******************************************************************************* * Copyright (c) 2010-2014 SAP AG and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors://from w w w . j a v a 2s. c o m * SAP AG - initial API and implementation *******************************************************************************/ import java.io.StringWriter; import javax.xml.transform.OutputKeys; 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; public class Main { /** * Transforms the given XML document into its textual representation. * * @param doc the document to transform. * @return the XML document transformed to a string. * * @throws TransformerException if the transformation failed. */ public static String documentToString(Document doc) throws TransformerException { StreamResult result = new StreamResult(new StringWriter()); transform(doc, result); String xmlString = result.getWriter().toString(); return xmlString; } private static void transform(Document doc, StreamResult result) throws TransformerException { DOMSource source = new DOMSource(doc); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ transformer.transform(source, result); } }