XSLT is Extensible Style Sheet Transformation which is used to transform/convert a XML to another HTML/XML structure with the help of XSL document.
In this example, we are going to convert 1.xml to 2.xml structure with the help of XSL document., in Java.
Steps:
Load the input XML inside the DOM parser as document.
Load the input XSL in a Stream.
Using the inbuilt DOM XML transformer in Java, transform the XML to another XML with the help of XSLT.
Input XML: (1.XML)
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="UTF-8"?> <Org> <Emp> <Name>Developer</Name> <ID>6260</ID> <Location>India</Location> </Emp> </Org> |
XSLT Tranformation File (2.XSL)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <Employee> <xsl:value-of select="Org/Emp/Name"/>- Appended Value: <xsl:value-of select="concat(Org/Emp/Name,' ',Org/Emp/ID, ' ',Org/Emp/Location )"/> </Employee> </xsl:template> </xsl:stylesheet> |
In the below Java Program, the above XML is transformed to the output XML., using the XSLT. XSLT provides the details such as where the values needs to be placed/ordered.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.w3c.dom.Document; public class DomXSLParsing { public static void main(String args[]) throws Exception{ new DomXSLParsing(); } public DomXSLParsing() throws Exception { String inputXML = "1.xml"; String inputXSL = "2.xsl"; String outputXML = "3.xml"; convertXMLusingXSL(inputXML, inputXSL, outputXML); } public void convertXMLusingXSL(String inputXML, String inputXSL, String outputXML) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(inputXML); doc.normalize(); StreamSource xsl = new StreamSource(new File(inputXSL)); TransformerFactory tf = TransformerFactory.newInstance(); tf.newTransformer(xsl).transform(new DOMSource(doc), new StreamResult(new File(outputXML))); } } |
The above Program applies the XSLT to the XML and generates the below XML as the output XML. (3.XML)
1 2 3 4 |
<?xml version="1.0" encoding="UTF-8"?> <Employee> Appended Value: Developer 25216 India </Employee> |