1

How can I get the XML generated by DOM parser to be stored in string variable in Java? I can store it in .xml file using:

// creating and writing to xml file  
TransformerFactory transformerFactory = TransformerFactory.newInstance();  
Transformer transformer = transformerFactory.newTransformer();  
DOMSource domSource = new DOMSource(document);  
StreamResult streamResult = new StreamResult(new File("d:/xml_created.xml"));
transformer.transform(domSource, streamResult);

but I need to get it stored in a string variable.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

2

You can create a StringWriter and print the XML to that:

http://docs.oracle.com/javase/7/docs/api/java/io/StringWriter.html

StringWriter sw = new StringWriter();

transformer.transform(domSource, sw);

String xml = sw.toString();

You may need to wrap the StringWriter in an OutputStream, I can't remember off hand.

Tim B
  • 40,716
  • 16
  • 83
  • 128