tags:

views:

39

answers:

1

I want to save my DOM Document as an XML file. I follow this tutorial: http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPXSLT4.html

So, this is my code:

...
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);

but instead of System.out, I want to save in a file the result. How can I do this?

+3  A: 

Use

new StreamResult(new FileOutputStream(...))

But you may want to use a Writer, so that you are outputting encoded characters, unless StreamResult is using a Unicode encoding, say UTF-8, implicitly.

Software Monkey
Use `InputStream` and `OutputStream` objects for XML, because XML describes its encoding internally. For example, create an `OutputStreamWriter` using the UTF-16 encoding. The `Transformer` can't auto-detect that, so it uses an "encoding" attribute of "UTF-8" in the `xml` declaration. When the resulting XML is parsed, a UTF-8 decoder is used as specified in the document, but it fails because the actual encoding is UTF-16. You can work around this by setting the `OutputKeys.ENCODING` property on the `Transformer`, but why bother?
erickson