Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to XML input stream in java

Tags:

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

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

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.

Please provide your suggestions.

like image 862
jobinbasani Avatar asked Oct 02 '09 16:10

jobinbasani


People also ask

Can we convert String to XML in Java?

Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion.

Can we convert String to stream in Java?

We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class. In ByteArrayInputStream there is an internal buffer present that contains bytes that reads from the stream.

How do you create an input stream from a String?

Basically we are going to : Get the bytes of the String. Create a new ByteArrayInputStream using the bytes of the String. Assign the ByteArrayInputStream object to an InputStream variable (which you can do as InputStream is a superclass of ByteArrayInputStream )

How do you convert an input stream into String in Java?

To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.


2 Answers

new StreamSource(new StringReader(str)) 
like image 159
Vladimir Dyuzhev Avatar answered Oct 05 '22 22:10

Vladimir Dyuzhev


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

I say you probably want a Reader rather than an InputStream because a String holds characters, not bytes, and an InputStream is a stream of bytes while a Reader is a stream of characters.

like image 39
Laurence Gonsalves Avatar answered Oct 06 '22 00:10

Laurence Gonsalves