14

I am doing some data conversion(like csv) to xml with SAX then using transformer in Java. The result is in StreamResult, and I am trying to save this result to a file.xml but I can't find way to save StreamResult into file. am I doing this all wrong?

Todd
  • 235
  • 2
  • 3
  • 6

2 Answers2

28

Your StreamResult should be created on the basis of a file, e.g.

StreamResult sr = new StreamResult(new File("/my/file.xml"));

If you give your Transformer such a StreamResult, it will write its result directly into the file you specified.

Carl Smotricz
  • 66,391
  • 18
  • 125
  • 167
3

I am not familiar with the API... but does this link give you what you are after?

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);

String xmlString = result.getWriter().toString();
System.out.println(xmlString);
TofuBeer
  • 60,850
  • 18
  • 118
  • 163
  • The comment does not match the code. It says it's saving to a File, but it actually writes to a String that gets println'd. – james.garriss Jul 15 '14 at 12:42