The xsl transformation is done to translate the xml file content to any file formats. Namely- html, xhtml, etc
The xslt transformation can be done statically by including the 'xsl file' name in the xml file. But here we achieve this at run time. The java xslt code gets the xml file, xsl file and an output file as input through command line.
xml-file.xml
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Age of Empires</title>
<artist>Eric</artist>
<country>India</country>
<company>Pearl</company>
<price>15.90</price>
<year>1983</year>
</cd>
</catalog>
xsl-file.xsl
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="catalog">
<html>
<head>
<xsl:for-each select="cd">
<xsl:if test="country = 'India'">
<title><xsl:value-of select="country"/></title>
</xsl:if>
</xsl:for-each>
</head>
<body>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
XSLTdemo.java
package xsltsample;
import java.io.File;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class XSLTdemo {
public XSLTdemo() {
}
public static void main(String[] args) {
File xmlfile = new File("/techhome/mahesh/javaprograms/XSLTSample/xml-file.xml");
File xslfile = new File("/techhome/mahesh/javaprograms/XSLTSample/xsl-file.xsl");
File outfile = new File("/techhome/mahesh/javaprograms/XSLTSample/output-file");
TransformerFactory tf = TransformerFactory.newInstance();
try {
Transformer t = tf.newTransformer(new StreamSource(xslfile));
Source s = new StreamSource(xmlfile);
Result r = new StreamResult(outfile);
t.transform(s, r);
} catch (TransformerConfigurationException ex) {
ex.printStackTrace();
} catch (TransformerException ex) {
ex.printStackTrace();
}
}
}
output-file
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>India</title>
</head>
<body></body>
</html>
No comments:
Post a Comment