In development we often use XML files as the carrier of data. When we get to an XML file we often want to extract its data or convert it to another format, we need to use XSLT at this point.
The full name of XSLT is extensible Stylesheet Language Transformations (Extensible Stylesheet Translation Language), and its most common function is to convert XML from one format to another. In this article we will convert an XML file that hosts famous people information into an HTML file. In. NET, you can use the XslCompiledTransform class to load an XSLT document and transform an XML document using an XSLT document. Examples are as follows:
XML document (People.xml) that hosts famous people information:
1 <?XML version= "1.0"?>2 <people>3 < Personborndate= "1874-11-30 dieddate=1965-01-24">4 <Name>Winston Churchill</Name>5 <Description>6 Winston Churchill is a mid-20th century British politician who7 became famous as Prime minister during the Second world War.8 </Description>9 </ Person>Ten < Person> One <Name>Indira Gandhi</Name> A <Description>Indira Gandhi was India's first female prime minister and was assassinated in 1984.</Description> - </ Person> - < Personborndate= "1917-05-29"dieddate= "1963-11-22"> the <Name>John F. Kennedy</Name> - <Description> - JFK, as he was affectionately known, was a and states President - Who is assassinated in Dallas, Texas. + </Description> - </ Person> + </people>
XSLT (PEOPLETOHTML.XSLT) for transforming the XML structure:
1 <Xsl:stylesheet2 xmlns:xsl= "Http://www.w3.org/1999/XSL/Transform"3 version= "1.0">4 <xsl:templateMatch="/">5 <HTML>6 <Head>7 <title>Famous people</title>8 </Head>9 <Body>Ten <H1>Famous peoples</H1> One <HR/> A <ul> - <Xsl:for-eachSelect= "People/person"> - <Li> the <xsl:value-ofSelect= "Name/text ()"/> - </Li> - </Xsl:for-each> - </ul> + </Body> - </HTML> + </xsl:template> A <xsl:templateMatch= "Person"> at <Li> - <xsl:value-ofSelect= "Name"/> - </Li> - </xsl:template> - </Xsl:stylesheet>
C # code:
1 Static voidMain (string[] args)2 {3XslCompiledTransform objxslt =NewXslCompiledTransform ();4Objxslt.load (@"peopletohtml.xslt");5Objxslt.transform (@"People.xml",@"people.html");6Process.Start (@"people.html");7 //pressqtoexist ();8}
Operation Result:
HTML source file content (people.html) generated after run:
1 <HTML>2 <Head>3 <METAhttp-equiv= "Content-type"content= "text/html; charset=utf-8">4 <title>Famous people</title>5 </Head>6 <Body>7 <H1>Famous peoples</H1>8 <HR>9 <ul>Ten <Li>Winston Churchill</Li> One <Li>Indira Gandhi</Li> A <Li>John F. Kennedy</Li> - </ul> - </Body> the </HTML>
This article is just a simple example of converting XML using the XslCompiledTransform class with XSLT in C #, where Xslcompliedtransform also accepts other constructor arguments, and XSLT can accept external parameters. These specific usages can be obtained by reviewing MSDN.
. NET to transform XML documents with XSLT