java - Document to StreamSource转换

tom*_*myk 1 java xslt dom

对于XSLT转换,我需要一个表示正在转换的xml文件的javax.xml.transform.stream.StreamSource对象.我只有一个org.w3c.dom.Document类型的对象.如何将Document转换为StreamSource?

tom*_*myk 8

我在这个网页上找到了一个解决方案.有一个DOMSource类,它将Document对象作为构造函数参数.

/**
 * 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();
}
Run Code Online (Sandbox Code Playgroud)