5

How to call XSL template from java code ?

Please note that, I don't need to know how to transform xml docuemnt by XSL in Java.

What I need exactly is that, I have some XSLT document that contains a template that do something, ex:

<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <tr>
        <td>.</td>
        <td>.</td>
      </tr>
    </table>
  </body>
  </html>
</xsl:template>

Then I need that template to be called from java code. How to ??

Thanks All guyz, I did it, Please see : http://m-hewedy.blogspot.com/2009/12/how-to-call-xslt-template-from-your.html

Muhammad Hewedy
  • 29,102
  • 44
  • 127
  • 219

3 Answers3

17

You can use the javax.xml.transformer.Transformer API for this.

Here's a basic kickoff example:

Source xmlInput = new StreamSource(new File("c:/path/to/input.xml"));
Source xsl = new StreamSource(new File("c:/path/to/file.xsl"));
Result xmlOutput = new StreamResult(new File("c:/path/to/output.xml"));

try {
    Transformer transformer = TransformerFactory.newInstance().newTransformer(xsl);
    transformer.transform(xmlInput, xmlOutput);
} catch (TransformerException e) {
    // Handle.
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • It also doesn't transfer. It transforms one XML to other XML based on the given XSLT. That's where XSL is for. What exactly do you need after all? You should have elaborated that in your question. You can eventually change the XML source and/or the XML result. – BalusC Dec 16 '09 at 16:35
  • Thanks, Please see the modified question above :) – Muhammad Hewedy Dec 16 '09 at 16:37
  • You've edited your topicstart. Sorry, I still don't forsee any problems. Maybe you just want to save the result as HTML. Just change the file extension accordingly, e.g. `output.html`. – BalusC Dec 16 '09 at 16:48
2

Here's some code for a simple XSL transform, along with some tips for using XSL in Java. And here's another example, complete with an example XML and XSL.

Kaleb Brasee
  • 51,193
  • 8
  • 108
  • 113
0

Is your question that you have an XSLT which doesn't require an input document? Then just give the Transformer object some kind of minimal document:

transformer.transform(new StreamSource(new StringReader("<empty/>")), yourResult);

Paul Clapham
  • 1,074
  • 5
  • 6