Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - Document to StreamSource conversion

Tags:

java

dom

xslt

For XSLT transformation I need a javax.xml.transform.stream.StreamSource object representing xml file being transformed. I have only an object of org.w3c.dom.Document type. How to convert Document to a StreamSource ?

like image 269
tommyk Avatar asked Nov 28 '25 20:11

tommyk


2 Answers

I found a solution on this web page. There is a DOMSource class which takes Document object as constructor parameter.

/**
 * Convert document to string for display
 * @param doc org.w3c.dom.Document
 * @return String
 */
private String documentToString(org.w3c.dom.Document doc) throws TransformerException {

    // Create dom source for the document
    DOMSource domSource=new DOMSource(doc);

    // Create a string writer
    StringWriter stringWriter=new StringWriter();

    // Create the result stream for the transform
    StreamResult result = new StreamResult(stringWriter);

    // Create a Transformer to serialize the document
    TransformerFactory tFactory =TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty("indent","yes");

    // Transform the document to the result stream
    transformer.transform(domSource, result);        
    return stringWriter.toString();
}
like image 62
tommyk Avatar answered Nov 30 '25 08:11

tommyk


In this context, you'll need to convert your Document back into some kind of stream (either character or bytes), in order for it to be processed as a StreamSource.

If the document is small, the easiest way might simply be to convert it into a string, create a StringReader over this and pass that reader to the StreamSource constructor. If the document is larger (or of unknown size) such that serializing it might take too much memory, you're going to have to create piped readers and writers in order to achieve the same thing (which is a pain due to the need to manage threads, but this is unavoidable if dumping the whole document temporarily is out).

An alternative approach might be to have a look where the Document came from in the first place. There's a reasonable chance that it arrived to your application as some sort of stream anyway. It may be easier to look at this step in the logic, and get the document's raw stream again for passing into the StreamSource, rather than reserializing the Document.

like image 24
Andrzej Doyle Avatar answered Nov 30 '25 10:11

Andrzej Doyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!