Java XML Transformer transform xml file
import java.io.FileInputStream; import java.io.InputStream; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; public class Main { public static void main(String[] args) throws Exception { InputStream xslInputStream = new FileInputStream("xslFile"); Source xslSource = new StreamSource(xslInputStream); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(xslSource); InputStream xmlInputStream = new FileInputStream("xmlFile"); StreamSource in = new StreamSource(xmlInputStream); StreamResult out = new StreamResult("outputFile"); transformer.transform(in, out);/*from ww w .j a v a2s . c o m*/ } }
languages.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="/"> <html> //from ww w . j ava 2s . c om <head> <title>Language</title> </head> <body> <table border="1"> <tr> <th>Id</th> <th>Name</th> <th>Feature</th> </tr> <xsl:for-each select="languages/language"> <tr> <td> <xsl:value-of select="@id"/> </td> <td> <xsl:value-of select="name"/> </td> <td> <xsl:value-of select="feature"/> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>
languages.xml
<?xml version="1.0" encoding="UTF-8"?> <languages> // w w w . j a v a 2 s. c o m <language id="1"> <name>CSS</name> <feature>style</feature> </language> <language id="2"> <name>Java</name> <feature>server</feature> </language> <language id="3"> <name>SQL</name> <feature>database</feature> </language> </languages>