在开发中我们经常用到xml文件作为数据的载体。当我们获取到一个XML文件后常常要将其数据提取出来或者将其转换为另一种格式,此时我们需要用到XSLT。
XSLT的全称是Extensible Stylesheet Language Transformations(可扩展样式表转换语言),其最常用的功能就是将XML从一种格式转换为另一种格式。本文中我们将把一个承载Famous People信息的xml文件转换成html文件。在.NET中可以使用XslCompiledTransform类加载XSLT文档并使用xslt文档对xml文档进行转换。示例如下:
承载Famous People信息的xml文档(people.xml):
1 <?xml version="1.0"?> 2 <People> 3 <Person bornDate="1874-11-30 diedDate=1965-01-24"> 4 <Name>Winston Churchill</Name> 5 <Description> 6 Winston Churchill was a mid-20th century British politician who 7 became famous as Prime Minister during the Second World War. 8 </Description> 9 </Person> 10 <Person> 11 <Name>Indira Gandhi</Name> 12 <Description>Indira Gandhi was India‘s first female prime minister and was assassinated in 1984.</Description> 13 </Person> 14 <Person bornDate="1917-05-29" diedDate="1963-11-22"> 15 <Name>John F. Kennedy</Name> 16 <Description> 17 JFK, as he was affectionately known, was a United States president 18 who was assassinated in Dallas, Texas. 19 </Description> 20 </Person> 21 </People>
用于转换XML结构的XSLT(PeopleToHtml.xslt):
1 <xsl:stylesheet 2 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 3 version="1.0"> 4 <xsl:template match="/"> 5 <html> 6 <head> 7 <title>Famous People</title> 8 </head> 9 <body> 10 <h1>Famous Peoples</h1> 11 <hr/> 12 <ul> 13 <xsl:for-each select="People/Person"> 14 <li> 15 <xsl:value-of select="Name/text()"/> 16 </li> 17 </xsl:for-each> 18 </ul> 19 </body> 20 </html> 21 </xsl:template> 22 <xsl:template match="Person"> 23 <li> 24 <xsl:value-of select="Name"/> 25 </li> 26 </xsl:template> 27 </xsl:stylesheet>
C#代码:
1 static void Main(string[] args) 2 { 3 XslCompiledTransform objXslt = new XslCompiledTransform(); 4 objXslt.Load(@"PeopleToHtml.xslt"); 5 objXslt.Transform(@"people.xml", @"people.html"); 6 Process.Start(@"people.html"); 7 //PressQToExist(); 8 }
运行结果:
运行后生成的html源文件内容(people.html):
1 <html> 2 <head> 3 <META http-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> 10 <li>Winston Churchill</li> 11 <li>Indira Gandhi</li> 12 <li>John F. Kennedy</li> 13 </ul> 14 </body> 15 </html>
本文只是一个在C#中用XslCompiledTransform类配合XSLT对XML进行转换的简单示例,其中XslCompliedTransform还接受其它的构造函数参数,以及XSLT也可以接受外部参数,这些具体用法可以通过查阅MSDN获取。
时间: 2024-10-08 05:30:37