Skip to content

Instantly share code, notes, and snippets.

@madankumarpc
Created July 27, 2012 08:15
Show Gist options
  • Save madankumarpc/3186803 to your computer and use it in GitHub Desktop.
Save madankumarpc/3186803 to your computer and use it in GitHub Desktop.
XML and XSLT explained made public
<?xml version="1.0" encoding="UTF-8"?>
<xml-body>
<books>
<book>
<name> Let us C </name>
<author> Yashvant kanetkar </author>
<year> 1990 </year>
<price> 100 </price>
</book>
<book>
<name> Let us C++ </name>
<author> Yashvant kanetkar </author>
<year> 1996 </year>
<price> 200 </price>
</book>
<book>
<name> Let us C# </name>
<author> Yashvant kanetkar </author>
<year> 2002 </year>
<price> 300 </price>
</book>
</books>
</xml-body>
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" indent="yes" />
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="books">
<table border="1" width="50%">
<xsl:for-each select="book">
<tr>
<td><xsl:value-of select="name"/> </td>
<td><xsl:value-of select="author"/> </td>
<td><xsl:value-of select="year"/> </td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
package com.test;
import java.io.FileNotFoundException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.FileOutputStream;
public class Xml2html {
public static void main(String[] args){
TransformerFactory tFact=TransformerFactory.newInstance();
Transformer t;
try {
t = tFact.newTransformer(new StreamSource("books.xsl"));
t.transform(new StreamSource("books.xml"), new StreamResult(new FileOutputStream("books.html")));
System.out.println("The output file is books.html");
} catch (TransformerConfigurationException e) {
System.out.println(e.getMessage());
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (TransformerException e) {
System.out.println(e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment