Tuesday, August 12, 2008

Convert Staxsource to StreamSource



import java.io.File;
import java.io.FileInputStream;
import java.io.StringReader;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class SourceConvertor
{
private static Source convertStaxToStream(Source request)
{
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = null;
File fp = null;
FileInputStream fInp = null;
try
{
transformer = factory.newTransformer();
fp = new File("tempFile.txt");
transformer.transform(request, new StreamResult(fp));
fInp = new FileInputStream(fp);
} catch (Exception e)
{
e.printStackTrace();
}
return new StreamSource(fInp);
}
public static void main(String args[])
{
try
{
String message ="RaiGodOfSmallThings";
Source original = new StreamSource(new StringReader(message));
Source converted = convertStaxToStream(original);

TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(converted, new StreamResult(System.out));
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

1 comments:

Anonymous said...

were you able to find a solution? I need a solution for this as well so i can receive the Source object and pass it on as an InputStream - but all we have access is to a StaxSource.
Let me know.
Thanks