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.
Let's create a sample console application to see how it works.
- 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.
- 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.
I have created the below XML which contains a note that is the main element and under this, it contains other elements.
XML
Requirement
We have created atransform file that generally has only 3 elements and also applied concatenation functionality for headings, separated by commas.
- 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 code
- <?xml version="1.0" encoding="utf-8"?>
- <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
- xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
- <xsl:output method="xml" indent="yes"/>
- <xsl:template match="/">
- <Details>
- <From>
- <xsl:value-of select="note/from"/>
- </From>
- <To>
- <xsl:value-of select="note/to"/>
- </To>
- <Heading>
- <xsl:value-of select="concat(note/heading1,', ',note/heading2)" />
- </Heading>
- </Details>
- </xsl:template>
- </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.
- Write the C# code to read the transform and XML files and generate the desired output XML.
- Result
Please check the output result.
Conclusion
I hope that you got an idea of how to use XSLT.