[英]Java Transformer: How do you make its result into an OutputStream?
我是javax.xml.transform.Transformer
新手。
我在XML
文檔上應用XSLT
,它工作正常。
我想要實現的是能夠將該轉換的輸出寫入OutputStream
。
這是我的代碼:
OutputStream outputStream = null;
InputStream agent = new FileInputStream("src/res/testxmlfile.xml");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource("src/res/trans.xslt"));
transformer.transform(new StreamSource(agent), outputStream ????????);
我知道它可以用來寫這樣的文件,但我想把它寫成一個OutputStream
對象。
transformer.transform(new StreamSource(agent),
new StreamResult(new FileOutputStream("/result.xml")));
如何傳遞OutputStream
來在這里使用?
這是我在傳遞Outputstream
時遇到的錯誤:
Exception in thread "main" javax.xml.transform.TransformerException:
Result object passed to ''{0}'' is invalid.
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
.getOutputHandler(TransformerImpl.java:468)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
.transform(TransformerImpl.java:344)
at com.gohealth.TestXmlStream.main(TestXmlStream.java:75)
使用StreamResult
。 它提供了構造函數來寫入File
或OutputStream
:
使用File
示例:
transformer.transform(new StreamSource(agent), new StreamResult(file));
使用FileOutputStream
示例:
FileOutputStream outputStream = new FileOutputStream(new File("outputfile.xml"));
transformer.transform(new StreamSource(agent), new StreamResult(outputStream));
使用ByteArrayOutputStream
示例:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
transformer.transform(new StreamSource(agent), new StreamResult(outputStream));
byte[] bytes = outputStream.toByteArray();`
使用由表示輸出所在位置的對象構造的“StreamResult”。 請參閱http://docs.oracle.com/javase/7/docs/api/javax/xml/transform/stream/StreamResult.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.