Java examples for XML:XML Transform
Converts an org.w3c.dom.Node to an XML string using an identity transform.
/*/* www. ja v a 2s.co m*/ * ElementNode * by Keith Gaughan <kmgaughan@eircom.net> * * Copyright (c) Keith Gaughan, 2006. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Common Public License v1.0, which accompanies this * distribution and is available at http://www.opensource.org/licenses/cpl1.0.php */ import java.io.StringWriter; import java.util.Arrays; import javax.xml.parsers.*; import javax.xml.transform.*; 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{ /** * Converts an <code>org.w3c.dom.Node</code> to an XML string using an * identity transform. * * @param node Node to convert. * * @return Node as an XML document. */ public static String toString(final Node node) { if (node == null) { return ""; } StringWriter writer = new StringWriter(); transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); } /** * Wraps up the nastiness that is the Java XML transformation API for * doing an identity transform, which allows an XML document to be * converted to a string. * * @param source Document source to convert. * @param result Object to which transformation is written. */ public static void transform(final Source source, final Result result) { final TransformerFactory tf; final Transformer t; try { tf = TransformerFactory.newInstance(); t = tf.newTransformer(); t.transform(source, result); } catch (Exception ex) { // Should *never* happen, but... throw new XmlException( "Could not do identity transform on XML document.", ex); } } }