Xsl transform in Java working example (xml to html)

In order to display XML documents, it is necessary to have a mechanism to describe how the document should be displayed. One of these mechanisms is Cascading Style Sheets (CSS), but XSL (eXtensibleStylesheet Language) is the preferred style sheet language of XML.
XSL can be used to define how an XML file should be displayed by transforming the XML file into a format such as HTML, PDF, etc..

Transforming an xml document to multiple views

In this example, i am going to transform a simple XML file into HTML.

Input XML file looks like.
user.xml :
<?xml version="1.0" encoding="utf-8"?>
<users>
  <user>
    <username>ganesh</username>
    <fname>Ganesh</fname>
    <lname>Tiwari</lname>
    <job>Software Developer</job>
    <address>Chitwan Nepal</address>
  </user>
  <user>
    <username>ramesh</username>
    <fname>Ramesh</fname>
    <lname>Tiwari</lname>
    <job></job>
    <address>Kathmandu Nepal</address>
  </user>
  <user>
    <username>Harihari</username>
    <fname>Hari</fname>
    <lname>Tiwari</lname>
    <job></job>
    <address>Kathmandu Nepal</address>
  </user>
</users>

And my XSL File, which lists the xml content into a table.

user.xsl :
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <h2>User Details</h2>
        <table border="1">
          <tr bgcolor="#9acd32">
            <th>FirstName</th>
            <th>LastName</th>
            <th>Job</th>
            <th>Address</th>
          </tr>
          <xsl:for-each select="users/user">
            <tr>
              <td>
                <xsl:value-of select="fname" />
              </td>
              <td>
                <xsl:value-of select="lname" />
              </td>
              <td>
                <xsl:value-of select="job" />
              </td>
              <td>
                <xsl:value-of select="address" />
              </td>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

Reusable class for XML-XSLT Transformation to Generate HTML: 

It has three public methods with input parameter as File, String or byte array. In java we can simply use javax.xml.transform package as XSL Processor. 

public class XmlTransform {
    public static String getTransformedHtml(File xmlFile, File xsltFile) throws TransformerException {
        byte[] xml = getStringFromFile(xmlFile).getBytes();
        byte[] xsl = getStringFromFile(xsltFile).getBytes();
        return getTransformedHtml(xml, xsl);
    }
    public static String getTransformedHtml(String xml, String xsl) throws TransformerException {
        return getTransformedHtml(xml.getBytes(), xsl.getBytes());
    }
    public static String getTransformedHtml(byte[] xml, byte[] xsl) throws TransformerException {
        Source srcXml = new StreamSource(new ByteArrayInputStream(xml));
        Source srcXsl = new StreamSource(new ByteArrayInputStream(xsl));
        StringWriter writer = new StringWriter();
        Result result = new StreamResult(writer);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(srcXsl);
        transformer.transform(srcXml, result);
        return writer.toString();
    }
    private static String getStringFromFile(File f) {
        StringBuilder sb = new StringBuilder(1000);
        try {
            Scanner sc = new Scanner(f);
            while (sc.hasNext()) {
                sb.append(sc.nextLine());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}

The test class
public class TestXsl {
     public static void main(String[] args) throws TransformerException {
         final File xmlFile = new File("user.xml");
         final File xsltFile = new File("user.xsl");
         System.out.println(XmlTransform.getTransformedHtml(xmlFile, xsltFile));
     }
}

The generated HTML:

<html>
<body>
<h2>User Details</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>FirstName</th><th>LastName</th><th>Job</th><th>Address</th>
</tr>
<tr>
<td>Ganesh</td><td>Tiwari</td><td>Software Developer</td><td>Chitwan Nepal</td>
</tr>
<tr>
<td>Ramesh</td><td>Tiwari</td><td></td><td>Kathmandu Nepal</td>
</tr>
<tr>
<td>Hari</td><td>Tiwari</td><td></td><td>Kathmandu Nepal</td>
</tr>
</table>
</body>
</html>

The HTML view of generated HTML:

User Details

FirstNameLastNameJobAddress
GaneshTiwariSoftware DeveloperChitwan Nepal
RameshTiwariKathmandu Nepal
HariTiwariKathmandu Nepal



2 comments :

  1. java code needs working on... e.g. System.out.println(XmlTransform.getTransformedHtml(xmlFile, xsltFile)); :)

    ReplyDelete

Your Comment and Question will help to make this blog better...