Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call XSL template from java code?

Tags:

java

xslt

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

like image 599
Muhammad Hewedy Avatar asked Dec 02 '22 06:12

Muhammad Hewedy


2 Answers

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.
}
like image 168
BalusC Avatar answered Dec 28 '22 08:12

BalusC


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.

like image 23
Kaleb Brasee Avatar answered Dec 28 '22 08:12

Kaleb Brasee