我是 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
:
使用文件
的例子:
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();`
关于Java 转换器 : How do you make its result into an OutputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26046608/