• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

redirect XML/DOM output to file??

 
R Harvey
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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" ...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic