To convert XML to another XML format using XSLT (Extensible
Stylesheet Language Transformations). It reads an XML file and applies an XSLT
stylesheet to transform the XML data into a different format, such as HTML.
Let's break down the code to understand its functionality
and purpose, and I'll also point out a few potential improvements.
Breakdown of the Key Components:
- Main
Functionality:
- The main
method loads the input XML from a file (breakFirst.xml) and an XSLT
stylesheet (breakFirst.xslt), then applies the transformation and outputs
the result.
- Converting
XML File to String:
- The
method convertXMLFileToString(String fileName) converts the XML file into
a string for easier processing. It uses the DocumentBuilderFactory to
read the XML file into a DOM object, then transforms it into a string
format.
- XSLT
Transformation:
- The transform(String
xmlDataInput, Templates xsltTemplate) method applies the XSLT stylesheet
to the provided XML data and returns the transformed result. The Templates
object is created using the XSLT file.
- Creating
the XSLT Template:
- createTemplate()
reads the XSLT file into a Templates object, which is then used for the
transformation.
Example Flow:
- You
have an XML file, breakFirst.xml, containing breakfast menu items, and an
XSLT stylesheet, breakFirst.xslt, which defines how to transform that XML
into an HTML page.
- The XmlToXmlConvert
class will read both the XML and XSLT, perform the transformation, and
output the transformed content.
Output:
In this case, the transformation will produce an HTML page
displaying the breakfast menu items styled with a teal background and white
text, as defined in the XSLT.
xslt
<?xml
version="1.0" encoding="UTF-8"?> <xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"> <xsl:output
indent="yes" method="html"/> <xsl:template
match="/"> <html> <body
style="font-family:Arial;font-size:12pt;background-color:#EEEEEE"> <xsl:for-each
select="breakfast_menu/food"> <div
style="background-color:teal;color:white;padding:4px"> <span
style="font-weight:bold"><xsl:value-of
select="name"/> - </span> <xsl:value-of
select="price"/> </div> <div
style="margin-left:20px;margin-bottom:1em;font-size:10pt"> <p> <xsl:value-of
select="description"/> <span
style="font-style:italic"> (<xsl:value-of
select="calories"/> calories per serving)</span> </p> </div> </xsl:for-each> </body> </html> </xsl:template> </xsl:stylesheet> |
xml
<?xml
version="1.0" encoding="UTF-8"?> <breakfast_menu> <food> <name>Belgian
Waffles</name> <price>$5.95</price> <description>Two
of our famous Belgian Waffles with plenty of real maple
syrup</description> <calories>650</calories> </food> <food> <name>Strawberry
Belgian Waffles</name> <price>$7.95</price> <description>Light
Belgian waffles covered with strawberries and whipped
cream</description> <calories>900</calories> </food> <food> <name>Berry-Berry
Belgian Waffles</name> <price>$8.95</price> <description>Light
Belgian waffles covered with an assortment of fresh berries and whipped
cream</description> <calories>900</calories> </food> <food> <name>French
Toast</name> <price>$4.50</price> <description>Thick
slices made from our homemade sourdough bread</description> <calories>600</calories> </food> <food> <name>Homestyle
Breakfast</name> <price>$6.95</price> <description>Two
eggs, bacon or sausage, toast, and our ever-popular hash
browns</description> <calories>950</calories> </food> </breakfast_menu> |
java
package
com.kartik.xml.to.xml; import
java.io.*; import
javax.xml.parsers.DocumentBuilderFactory; import
javax.xml.transform.*; 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) { try { // Convert XML file to string String dataXML =
convertXMLFileToString("C:\\Users\\kmandal\\Desktop\\breakFirst.xml"); // Create XSLT template Templates xsltTemplate =
createTemplate("C:\\Users\\kmandal\\Desktop\\breakFirst.xslt"); // Perform the transformation XmlToXmlConvert converter = new
XmlToXmlConvert(); String output =
converter.transform(dataXML, xsltTemplate); // Output the transformed content System.out.println(output); } catch (Exception e) { e.printStackTrace(); } } /** * Transform XML using XSLT template * @param xmlDataInput - XML data as
string * @param xsltTemplate - XSLT template
for transformation * @return Transformed XML or HTML as
string */ public String transform(String
xmlDataInput, Templates xsltTemplate) { if (xmlDataInput == null ||
xmlDataInput.trim().isEmpty() || xsltTemplate == null) { return null; } try (StringWriter stringWriter = new
StringWriter()) { Transformer transformer =
xsltTemplate.newTransformer(); StreamSource source = new
StreamSource(new StringReader(xmlDataInput)); StreamResult result = new
StreamResult(stringWriter); transformer.transform(source,
result); return stringWriter.toString(); } catch (Exception e) { throw new
RuntimeException("Error in XSLT transformation", e); } } /** * Create an XSLT template from a file * @param xsltFilePath - Path to XSLT
file * @return XSLT Template object * @throws Exception in case of error */ public static Templates
createTemplate(String xsltFilePath) throws Exception { TransformerFactory tFactory =
TransformerFactory.newInstance(); try (FileReader reader = new
FileReader(xsltFilePath)) { StreamSource stylesource = new
StreamSource(reader); return
tFactory.newTemplates(stylesource); } catch (Exception e) { throw new
RuntimeException("Error in creating XSLT template", e); } } /** * Convert an XML file to a string * @param fileName - Path to XML file * @return XML as string * @throws Exception in case of error */ public static String
convertXMLFileToString(String fileName) throws Exception { DocumentBuilderFactory
documentBuilderFactory = DocumentBuilderFactory.newInstance(); try (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(); } } } |
Output
<html> <body
style="font-family:Arial;font-size:12pt;background-color:#EEEEEE"> <div
style="background-color:teal;color:white;padding:4px"> <span
style="font-weight:bold">Belgian Waffles -
</span>$5.95</div> <div
style="margin-left:20px;margin-bottom:1em;font-size:10pt"> <p>Two
of our famous Belgian Waffles with plenty of real maple syrup<span
style="font-style:italic"> (650 calories per
serving)</span> </p> </div> <div
style="background-color:teal;color:white;padding:4px"> <span
style="font-weight:bold">Strawberry Belgian Waffles -
</span>$7.95</div> <div
style="margin-left:20px;margin-bottom:1em;font-size:10pt"> <p>Light
Belgian waffles covered with strawberries and whipped cream<span
style="font-style:italic"> (900 calories per
serving)</span> </p> </div> <div
style="background-color:teal;color:white;padding:4px"> <span
style="font-weight:bold">Berry-Berry Belgian Waffles -
</span>$8.95</div> <div
style="margin-left:20px;margin-bottom:1em;font-size:10pt"> <p>Light
Belgian waffles covered with an assortment of fresh berries and whipped
cream<span style="font-style:italic"> (900 calories per
serving)</span> </p> </div> <div
style="background-color:teal;color:white;padding:4px"> <span
style="font-weight:bold">French Toast -
</span>$4.50</div> <div
style="margin-left:20px;margin-bottom:1em;font-size:10pt"> <p>Thick
slices made from our homemade sourdough bread<span
style="font-style:italic"> (600 calories per
serving)</span> </p> </div> <div
style="background-color:teal;color:white;padding:4px"> <span
style="font-weight:bold">Homestyle Breakfast -
</span>$6.95</div> <div
style="margin-left:20px;margin-bottom:1em;font-size:10pt"> <p>Two
eggs, bacon or sausage, toast, and our ever-popular hash browns<span
style="font-style:italic"> (950 calories per
serving)</span> </p> </div> </body> </html> |
Key Changes:
- Exception
Handling: Improved error handling with try-catch blocks.
- File
Handling: Used try-with-resources to automatically close file streams.
- Flexibility:
File paths for XML and XSLT are passed as parameters.
This version reads the XML and XSLT files, applies the transformation, and prints the transformed result. You can save the result to an HTML file if required.
0 Comments