开发者

java - Document to StreamSource conversion

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 ?


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();
}


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.


Acts as an holder for a transformation Source in the form of a stream of XML markup.

A Streamsource wraps a stream of xml tokens. So you simply have to serialize the document to xml.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜