How to transform XML files using XSLT (Extensible Stylesheet
Language Transformations) in Java. The transformation process involves
converting one XML structure into another, for example, transforming the investments
XML format into a portfolio format or vice versa, as per the XSLT stylesheets
provided. Let's break down the key parts of this code and its significance:
Java
package
com.kartik.xml.to.xml; import
java.io.File; import
java.io.FileInputStream; import
java.io.InputStream; import
java.io.StringReader; import
java.io.StringWriter; import
javax.xml.parsers.DocumentBuilderFactory; import
javax.xml.transform.Templates; import
javax.xml.transform.Transformer; import
javax.xml.transform.TransformerConfigurationException; import
javax.xml.transform.TransformerException; import
javax.xml.transform.TransformerFactory; import
javax.xml.transform.dom.DOMSource; import
javax.xml.transform.stream.StreamResult; import
javax.xml.transform.stream.StreamSource; public class
XmlToXmlConvert { public static void main(String[] args) { String dataXML =
convertXMLFileToString("C:\\Users\\kmandal\\Desktop\\xxx.xml"); Templates input =createTemplate(); XmlToXmlConvert st = new
XmlToXmlConvert();
System.out.println(st.transform(dataXML, input)); /* String inputXSL =
convertXMLFileToString("C:\\Users\\kmandal\\Desktop\\breakFirst.xslt"); String outputHTML =
"C:\\Users\\kmandal\\Desktop\\break.html"; try{ st.transform(dataXML, inputXSL,
outputHTML); }catch
(TransformerConfigurationException e){
System.err.println("TransformerConfigurationException"); // System.err.println(e); }catch (TransformerException e){
System.err.println("TransformerException"); // System.err.println(e); }*/ } public void transform(String dataXML,
String inputXSL, String outputHTML)throws
TransformerConfigurationException,TransformerException { TransformerFactory factory =
TransformerFactory.newInstance(); StreamSource xslStream = new
StreamSource(inputXSL); Transformer transformer =
factory.newTransformer(xslStream); StreamSource in = new
StreamSource(dataXML); StreamResult out = new
StreamResult(outputHTML); transformer.transform(in, out); System.out.println("The
generated HTML file is:" + outputHTML); } /** * Transform xml using pfile to String * @param xmlDataInput * @param xsltTemplate * @return */ public String transform(String
xmlDataInput, Templates xsltTemplate) { if ( xmlDataInput == null ||
xmlDataInput.trim().length() == 0 || xsltTemplate == null) { return null; } StringWriter stringWriter = new
StringWriter(); try { Transformer transformer =
xsltTemplate.newTransformer(); StreamSource source = new StreamSource(new
StringReader(xmlDataInput)); javax.xml.transform.stream.StreamResult
result = new javax.xml.transform.stream.StreamResult( stringWriter); transformer.transform(source, result); } catch (TransformerConfigurationException
tce) { throw new RuntimeException("Error in
XSLT rule transformation"); } catch (TransformerException te) { throw new RuntimeException("Error in
XSLT rule transformation"); } return stringWriter.getBuffer().toString(); } /** * * @return */ public static Templates createTemplate(){ TransformerFactory tFactory =
TransformerFactory.newInstance(); // String xslt = getXslt();//this is
read from properties file String xslt =
convertXMLFileToString("C:\\Users\\kmandal\\Desktop\\xxx.xslt"); if ( xslt != null ) { StreamSource stylesource = new
StreamSource(new StringReader(xslt)); try { return
tFactory.newTemplates(stylesource); } catch
(TransformerConfigurationException e) {
System.out.println("Error"); } } return null; } /** * * @param fileName * @return */ public static String
convertXMLFileToString(String fileName) { try{ DocumentBuilderFactory
documentBuilderFactory = DocumentBuilderFactory.newInstance(); InputStream inputStream = new
FileInputStream(new File(fileName)); org.w3c.dom.Document doc =
documentBuilderFactory.newDocumentBuilder().parse(inputStream); StringWriter stw = new
StringWriter(); Transformer serializer =
TransformerFactory.newInstance().newTransformer(); serializer.transform(new
DOMSource(doc), new StreamResult(stw)); return stw.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } } |
Key Components of the Code
- XML
to XML Conversion: The Java program takes XML input, applies an XSLT
transformation, and outputs the transformed XML. This is useful when you
need to convert between different XML formats. For example, converting an
XML that represents stock data in one structure to a different structure.
- Templates
Object: The Templates object is created by reading an XSLT file (xxx.xslt).
This object is used to transform XML input using the TransformerFactory.newTemplates
method.
- Transformer
Object: The Transformer object is instantiated with the XSLT file, and
it is used to apply the XSL transformation to the XML data.
- Conversion
from XML File to String: The convertXMLFileToString method reads the
XML file from the file system and converts it into a String. This string
is used as input for the transformation process.
- Transformation
Process: The transform method is the core of the program, which takes
the XML input and applies the XSLT transformation using the Templates
object. It outputs the result as a string.
The XSLT Files
- Investments
to Portfolio: The XSLT transforms the investments XML format into the portfolio
format:
Xml
<?xml
version="1.0"?> <investments> <item type="stock"
exch="nyse"
symbol="ZCXM" company="kartik corp" price="28.875"/> <item type="stock"
exch="nasdaq" symbol="ZFFX" company="chandra
inc" price="92.250"/> <item type="stock"
exch="nasdaq" symbol="ZYSZ" company="mandal
inc" price="20.313"/> </investments> |
xslt
<?xml
version="1.0"?> <xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"> <xsl:output
method="xml" indent="yes"/> <xsl:template
match="/"> <portfolio> <xsl:for-each
select="investments/item[@type='stock']"> <stock> <xsl:attribute
name="exchange"> <xsl:value-of
select="@exch"/> </xsl:attribute> <name><xsl:value-of
select="@company"/></name> <symbol><xsl:value-of
select="@symbol"/></symbol> <price><xsl:value-of
select="@price"/></price> </stock> </xsl:for-each> </portfolio> </xsl:template> </xsl:stylesheet> |
- Portfolio
to Investments: The reverse transformation from portfolio to investments
format:
Xml
<?xml
version="1.0"?> <portfolio> <stock exchange="nyse"> <name>kartik corp</name> <symbol>ZCXM</symbol> <price>28.875</price> </stock> <stock exchange="nasdaq"> <name>chandra inc</name> <symbol>ZFFX</symbol> <price>92.250</price> </stock> <stock exchange="nasdaq"> <name>mandal inc</name> <symbol>ZYSZ</symbol> <price>20.313</price> </stock> </portfolio> |
xslt
<?xml
version="1.0"?> <xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output
method="xml" indent="yes"/> <xsl:template
match="/"> <investments> <xsl:for-each
select="portfolio/stock"> <item type="stock"> <xsl:attribute
name="exch"><xsl:value-of
select="@exchange"/></xsl:attribute> <xsl:attribute
name="symbol"><xsl:value-of
select="symbol"/></xsl:attribute> <xsl:attribute
name="company"><xsl:value-of
select="name"/></xsl:attribute> <xsl:attribute
name="price"><xsl:value-of
select="price"/></xsl:attribute> </item> </xsl:for-each> </investments> </xsl:template> </xsl:stylesheet> |
Usage in Real-Life Applications
This approach is useful in scenarios like:
- Data
Exchange: Converting XML data from one format to another when
integrating with different systems.
- Data
Processing: In financial applications where stock or investment data
needs to be consumed in various formats.
- Content Management: When transforming XML documents in web services or content management systems.
0 Comments