aspose file tools*
The moose likes I/O and Streams and the fly likes redirect XML/DOM output to file?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "redirect XML/DOM output to file??" Watch "redirect XML/DOM output to file??" New topic
Author

redirect XML/DOM output to file??

R Harvey
Greenhorn

Joined: Sep 17, 2002
Posts: 20
Hi.
I've built a program to create a large DOM tree from a database. I need to be able to write this dom tree out to a file as XML, and i have only found code to send it to system.out(). Is there a way i can re-direct this to a file??? Here is the chunk of code i'm using:
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(DOM);
StreamResult result = new StreamResult(System.out); //Here it is!!!
transformer.transform(source, result);
}
etc.....
At the moment, i can create a file like this:
$ java myProgram > file.xml
But i'd rather specify a file name as an argument to the command.
Many thanks for any help!!!
Robin
R Harvey
Greenhorn

Joined: Sep 17, 2002
Posts: 20
Errrmmm.... DOH!!!
At the risk of looking a bit stoopid, i'll answer my own question. Change the code to be:
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(DOM);
StreamResult result = new StreamResult(new File("c:\\temp\\test-out.xml"));
transformer.transform(source, result);
..... and voila!!! I found the info on the sun site, by searching goole for StreamResult.
Thanks for my help!
Robin
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Good find! The substitutability of streams is pretty neat. I've been building an HTTP server that reads from a socket and writes some stuff to disk. But for unit testing, it reads from a ByteArrayInputStream that I create in my test, and writes to a ByteArrayOutputStream that I can convert to string and compare to the expected results.
Re "Thanks for my help" ...


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: redirect XML/DOM output to file??