Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Saving StreamResult to a file

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?

like image 947
Todd Avatar asked Dec 21 '09 01:12

Todd


People also ask

How to convert StreamResult into file in Java?

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.

What is StreamResult in Java?

public class StreamResult extends Object implements Result. Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup.

How read and write data from XML in Java?

We must have followed the process to read an XML file in Java: Instantiate XML file: DOM parser loads the XML file into memory and consider every tag as an element. Get root node: Document class provides the getDocumentElement() method to get the root node and the element of the XML file.


2 Answers

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.

like image 159
Carl Smotricz Avatar answered Oct 23 '22 05:10

Carl Smotricz


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);
like image 29
TofuBeer Avatar answered Oct 23 '22 05:10

TofuBeer