在做使用XSL+XML生成HTML時遇到一個問題,網上搜索到的代碼大多以讀一個文件路徑的方式讀取xsl文件(來源:http://www.blogjava.net/yangxiang/archive/2009/08/11/290688.html),
Source xslSource = new StreamSource(xslFileName);
但是我最終是要把方法wrap成一個custom component,xsl是通過一個Document變量傳進來,於是嘗試採用如下方法讀xsl文件:
Source xslSource = new DOMSource(xslDoc);
執行沒有出錯,但是生成的html沒有包含xml裏面數據,總之結果不正確。於是想辦法把Document轉換成一個stream後按Source xslSource = new StreamSource(xslFileName);同樣方法讀取Source。
以下是將Document轉換成ByteArrayInputStream的方法:
public static ByteArrayInputStream ConvertDoc2Stream(org.w3c.dom.Document myDoc){
ByteArrayInputStream byteStream = null;
try{
TransformerFactory transFactory=TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
DOMSource source = new DOMSource();
source.setNode(myDoc);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
StreamResult result = new StreamResult();
result.setOutputStream(outputStream);
transformer.transform(source, result);
byteStream = new ByteArrayInputStream(outputStream.toByteArray());
}catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteStream;
}