1

I can now generate an HTML file using the code:

FileInputStream xml = new FileInputStream("original.xml");  
FileInputStream xsl = new FileInputStream("converter.xsl");
FileOutputStream out = new FileOutputStream("result.html");

Source xmlDoc =  new StreamSource(xml);
Source xslDoc =  new StreamSource(xsl);
Result result =  new StreamResult(out);

TransformerFactory factory = TransformerFactory.newInstance();            
Transformer trans = factory.newTransformer(xslDoc);
trans.transform(xmlDoc, result); 

However, I want to generate a Java String instead of an external HTML file, so that I can pass the result back to my JSP page by Ajax callback. How can I modify this code to do that?

3
  • There's nothing in your code that specifies that HTML is what comes out (except perhaps the name of the output file). It all comes down to the XSL file - what it converts your XML into. With a different XSL file, this could generate something completely different. Commented Feb 9, 2014 at 21:06
  • @DavidWallace Well that's true. What I'm wondering about is how to replace that FileOutputStream with some String thing. It seems that the construction of StreamResult is very restricted. Commented Feb 9, 2014 at 21:12
  • @goldfrapp04: Have you tried the ByteArrayOutputStream below? Commented Feb 9, 2014 at 21:13

2 Answers 2

2

Replace the FileOutputStream with a StringWriter, then call toString() on the StringWriter at the end. Something like this.

FileInputStream xml = new FileInputStream("original.xml");  
FileInputStream xsl = new FileInputStream("converter.xsl");
StringWriter writer = new StringWriter();

Source xmlDoc =  new StreamSource(xml);
Source xslDoc =  new StreamSource(xsl);
Result result =  new StreamResult(writer);

TransformerFactory factory = TransformerFactory.newInstance();            
Transformer trans = factory.newTransformer(xslDoc);
trans.transform(xmlDoc, result); 

String outputString = writer.toString();
Sign up to request clarification or add additional context in comments.

Comments

0

Simply change the type of variable out to ByteArrayOutputStream

ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.toString() // Should do the job

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.