top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What XSLT Transformation Is And How To Use It

0 votes
259 views

Introduction

XSLT (Extensible Stylesheet Language Transformations) is a language for transforming XML documents into other XML documents. Sometimes, the user wants some kind of XML structure instead of the whole XML. In that case, we can use XSLT transformation. This article will give us an idea about this.

Please have a look at the below image of the high-level structure.

XSLT

Let's create a sample console application to see how it works.

  1. Create a console application. Open Visual Studio - File - New Project - Console Application; give it a suitable name, such as - ‘XSLT_XML_Transformation’ and click OK.

    XSLT

 

  1. Let's create a main XML, i.e., input.xml. Right click on ‘Solution Explorer’ - Add - New Item and select XML file; give it a name like input.xml.

    XSLT

    I have created the below XML which contains a note that is the main element and under this, it contains other elements.

XML

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <note>  
  3.     <from>sagar@gmail.com</from>  
  4.     <to>swapnil@gmail.com</to>  
  5.     <cc>pankaj@gmail.com</cc>  
  6.     <bcc>amit@gmail.com</bcc>  
  7.     <heading1>Reminder</heading1>  
  8.     <heading2>Important</heading2>  
  9.     <body>Don't forget me this weekend!</body>      
  10. </note>  

Requirement

We have created  atransform file that generally has only 3 elements and also applied concatenation functionality for headings, separated by commas.

 

 

  1. Now, create an XSLT transform file to match the above requirement. Right-click on ‘Solution Explorer’ - Add - New Item and select XSLT File and give it a name like transform.xslt.

    XSLT

    XSLT code
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  
  3.     xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">  
  4.     <xsl:output method="xml" indent="yes"/>  
  5.     <xsl:template match="/">  
  6.         <Details>  
  7.             <From>  
  8.                 <xsl:value-of select="note/from"/>  
  9.             </From>  
  10.             <To>  
  11.                 <xsl:value-of select="note/to"/>  
  12.             </To>  
  13.             <Heading>  
  14.                 <xsl:value-of select="concat(note/heading1,', ',note/heading2)" />  
  15.             </Heading>  
  16.         </Details>  
  17.     </xsl:template>  
  18. </xsl:stylesheet>  

Some summary of XSLT functions is as below.

    • <xsl:value-of> – The <xsl:value-of> element is used to extract the value of a selected node.
    • Concat – The fn:concat function requires at least two arguments (which can be the empty sequence), and accepts an unlimited number of additional arguments.
    • <xsl:for-each> - The <xsl:for-each> element allows you to do looping in XSLT
    • <xsl:if> - The <xsl:if> element is used to put a conditional test against the content of the XML file
    • <xsl:choose> - The <xsl:choose> element is used in conjunction with <xsl:when> and <xsl:otherwise> to express multiple conditional tests
    • format-number() - The format-number() function is used to convert a number into a string.

 

  1. Write the C# code to read the transform and XML files and generate the desired output XML.

    XSLT

 

  1. Result 
    Please check the output result.
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <Details>  
    3.   <From>sagar@gmail.com</From>  
    4.   <To>swapnil@gmail.com</To>  
    5.   <Heading>Reminder, Important</Heading>  
    6. </Details>  

 

Conclusion

    I hope that you got an idea of how to use XSLT.

    posted Jan 10, 2018 by Shivaranjini

      Promote This Article
    Facebook Share Button Twitter Share Button LinkedIn Share Button


    Related Articles

    This article describes how to transform the XML output of SQL query statements using FOR XML AUTO to HTML using XSLT.

    Normally, we execute the query using ExecuteNonQuery statement and fill the output into a data table. We can access the data in the data table by giving column name and row number in the looping method. This makes us work on extra coding and takes a lot of time to get the correct data from executed query. So, I moved to XML because, in XML, we can fetch the values easily and quickly without writing too much code.     

    FOR XML Clause in SQL

    Basically, we have four types of FOR XML clause in SQL.

    • FOR XML RAW
    • FOR XML AUTO
    • FOR XML EXPLICIT
    • FOR XML PATH

    Each of the above types satisfies its own need. When you want full control over the produced XML, you use FOR XML EXPLICIT, but it is difficult to understand, read, or maintain. FOR XML AUTO produces the most readable SELECT statement. The RAW option is rarely used and therefore not discussed. The PATH option allows you to mix attributes and elements easier. Here, I gona use FOR XML AUTO.

    Table Name - Contact_Details

    Contact_IDContact_NumberContact_NameContact_Location
    001088888888MohanChennnai
    002099999999AbilashBangalore


    If we want the output as in XML format, we need to add the FOR XML AUTO statement.

     

    1. SELECT * FROM Contact_Details FOR XML AUTO  

    This query gives the output like,

    1. < Contact_Details Contact_ID=’001’ Contact_Number=’ 088888888’ Contact_Name=’Mohan’ Contact_Location=’Chennai’/>  
    2. < Contact_Details Contact_ID=’002’ Contact_Number=’ 099999999’ Contact_Name=’Abilash’ Contact_Location=’Bangalore’/>  

    The XML which we got in output is not in user-friendly format. We need each field as an attribute so, that we can access the values using XPATH. To achieve that, we need to add the ELEMENTS parameter with the query.

     

    1. SELECT * FROM Contact_Details FOR XML AUTO, ELEMENTS  

    This query gives the output like,

    1. < Contact_Details>  
    2.     <Contact_ID>001</Contact_ID>  
    3.     <Contact_Number>088888888</Contact_Number>  
    4.     <Contact_Name>Mohan</Contact_Name>  
    5.     <Contact_Location>Chennai</Contact_Location>  
    6. </ Contact_Details>  
    7. < Contact_Details>  
    8.     <Contact_ID>002</Contact_ID>  
    9.     <Contact_Number>099999999</Contact_Number>  
    10.     <Contact_Name>Abilash</Contact_Name>  
    11.     <Contact_Location>Bangalore</Contact_Location>  
    12. </ Contact_Details>  

    So, this is the exact XML format we need.

    Now, we are going to create XML DOCUMENT and write this output XML into that XML document in coding. To read the query in XML format, we need to execute the query using ExecuteXmlReader() function. 

    1. XmlReader XMLReader = new XmlReader();  
    2. XmlDocument XmlDoc = new XmlDocument();  
    3. SqlCommand Cmd = new SqlCommand(Query, Conn);  
    4. XMLReader = cmd.ExecuteXmlReader();  
    5. XPathDocument xPathDoc = new XPathDocument(XMLReader);  
    6. XPathNavigator xPathNavi = xPathDoc.CreateNavigator();  
    7. XmlDoc.LoadXml(XpathNavi.OuterXml);  

    Now, we got the full structured XML Document. Using this, we will transform the data into HTML format using XSLT.

    Before transforming, we need to create one XSLT file to assign the values from XMLDocument to HTML format.

    Contact_Details.xslt

    1. <?xml version=”1.0” encoding=”utf-8”?>  
    2. <xsl:stylesheet version=”1.0” xmlns:xsl=”http://www.w3.org/1999/XSL/Tranform”>  
    3.     <xsl:output method=”xml” indent=”yes” omit-xml-declaration=”yes”>  
    4.         <xsl:template match=”/*”>  
    5.             <table>  
    6.                 <tr>// Column heading  
    7.                     <td>ContactID</td>  
    8.                     <td>ContactNumber</td>  
    9.                     <td>ContName</td>  
    10.                     <td>ContactLocation</td>  
    11.                 </tr>  
    12.                 <xsl:for-each select=”/ Contact_Details”>  
    13.                     <tr>// inserting XML data into HTML table  
    14.                         <td>  
    15.                             <xsl:value-of select=”/Contact_details/Contact_ID” </td> // using XPath we can access the value from XML Document  
    16.                                 <td>  
    17.                                     <xsl:value-of select=”/Contact_details/Contact_Number” </td>  
    18.                                 <td>  
    19.                               <xsl:value-of select=”/Contact_details/Contact_Name” </td>  
    20.                           <td>  
    21.                        <xsl:value-of select=”/Contact_details/Contact_Location” </td>  
    22.                     </tr>  
    23.                 </xsl:for-each>  
    24.             </table>  
    25.         </xsl:template>  
    26. </xsl:stylesheet>  

    Now, we have XML Document and XSLT file. In the next step, we are going to transform the XML Document into HTML using XSLT. To do this, we pass the XMLDocument and XSLT file to separate functions and get fully formed HTML strings in return.

    1. Public static string TransformXMLTOHTML(XmlDocument XMLDoc, String XSLTFilename) {  
    2.     StringWriter HTMLString = new StringWriter();  
    3.     XslCompiledTransform Xmltransform = new XslCompiledTransform();  
    4.     XmlTransform.Load(XSLTFilename); // Load XSLT File  
    5.     Xmltranform.Transform(XMLDoc, null, Result); // transform XML into HTML  
    6.     Return HTMLString.ToString();  
    7. }  
    READ MORE
    ...