Skip to content

Instantly share code, notes, and snippets.

@sivaprasadreddy
Created June 7, 2012 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sivaprasadreddy/2886393 to your computer and use it in GitHub Desktop.
Save sivaprasadreddy/2886393 to your computer and use it in GitHub Desktop.
XMLUtils to print XML Document Object as String
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* @author Siva
*
*/
public class XMLUtils
{
public static void main(String[] args)
{
String xml = "<tag><nested>hello</nested></tag>";
Document document = getStringAsXmlDocument(xml);
System.out.println(getDocumentAsString(document));
}
public static String getDocumentAsString(Document document)
{
String output = null;
try
{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
output = writer.getBuffer().toString();
} catch (Exception e)
{
//e.printStackTrace();
throw new RuntimeException(e);
}
return output;
}
public static Document getStringAsXmlDocument(String xml)
{
Document xmlDoc = null;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource sourceXML = new InputSource(new StringReader(xml));
xmlDoc = db.parse(sourceXML);
} catch (Exception e)
{
//e.printStackTrace();
throw new RuntimeException(e);
}
return xmlDoc;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment