Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'transform' a String object (containing XML) to an element on an existing JSP page

Tags:

java

xml

xslt

Currently, I have a String object that contains XML elements:

String carsInGarage = garage.getCars();

I now want to pass this String as an input/stream source (or some kind of source), but am unsure which one to choose and how to implement it.

Most of the solutions I have looked at import the package: javax.xml.transform and accept a XML file (stylerXML.xml) and output to a HTML file (outputFile.html) (See code below).

try 
{
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(new StreamSource("styler.xsl"));

    transformer.transform(new StreamSource("stylerXML.xml"), new StreamResult(new FileOutputStream("outputFile.html")));
}
catch (Exception e)
{
    e.printStackTrace();
}

I want to accept a String object and output (using XSL) to a element within an existing JSP page. I just don't know how to implement this, even having looked at the code above.

Can someone please advise/assist. I have searched high and low for a solution, but I just can't pull anything out.

like image 204
Lycana Avatar asked May 12 '09 09:05

Lycana


1 Answers

Use a StringReader and a StringWriter:

try {
    StringReader reader = new StringReader("<xml>blabla</xml>");
    StringWriter writer = new StringWriter();
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(
            new javax.xml.transform.stream.StreamSource("styler.xsl"));

    transformer.transform(
            new javax.xml.transform.stream.StreamSource(reader), 
            new javax.xml.transform.stream.StreamResult(writer));

    String result = writer.toString();
} catch (Exception e) {
    e.printStackTrace();
}
like image 117
bruno conde Avatar answered Nov 05 '22 03:11

bruno conde