在java中将字符串转换为XML输入流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1510712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:39:44  来源:igfitidea点击:

Convert a string to XML input stream in java

javaapache-fop

提问by jobinbasani

I'm trying to generate a PDF document using FOP and Java.

我正在尝试使用 FOP 和 Java 生成 PDF 文档。

I receive the XML as a string and not as a file.

我将 XML 作为字符串而不是文件接收。

How can I convert this XML string to an XML input stream so that I can call xslfoTransformer.transform(source, res); where source is my XML string as an Input stream.

如何将此 XML 字符串转换为 XML 输入流,以便我可以调用 xslfoTransformer.transform(source, res); 其中 source 是我的 XML 字符串作为输入流。

Please provide your suggestions.

请提供您的建议。

采纳答案by Laurence Gonsalves

You probably want to convert it to a Reader, not an InputStream. Use StringReaderto do this. StreamSource has a constructor that takes a Reader, and you can pass that StreamSourceto Transformer.transform().

您可能想将其转换为 aReader而不是InputStream。使用StringReader来做到这一点。StreamSource 有一个接受 Reader 的构造函数,您可以将它传递StreamSource给 Transformer.transform()。

I say you probably want a Readerrather than an InputStreambecause a String holds characters, not bytes, and an InputStreamis a stream of bytes while a Readeris a stream of characters.

我说你可能想要 aReader而不是 anInputStream因为 String 保存字符,而不是字节,并且 anInputStream是字节流而 aReader是字符流。

回答by ChssPly76

Use ByteArrayInputStream:

使用ByteArrayInputStream

String S = ...;
InputStream source = new ByteArrayInputStream(S.getBytes(encoding))

回答by Vladimir Dyuzhev

new StreamSource(new StringReader(str))