C#实现XSL转换的方法
本文实例讲述了C#实现XSL转换的方法。分享给大家供大家参考,具体如下:
xsl可方便的将一种格式的xml,转换成另一种格式的xml,参考下面的代码:
usingSystem; usingSystem.IO; usingSystem.Text; usingSystem.Xml; usingSystem.Xml.Xsl; namespaceXslLoad { classProgram { staticvoidMain(string[]args) { stringxml=@"<?xmlversion='1.0'encoding='ISO-8859-1'?> <catalog> <cd> <title>EmpireBurlesque</title> <artist>BobDylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> </catalog>"; stringxsl=@"<?xmlversion='1.0'encoding='ISO-8859-1'?> <xsl:stylesheetversion='1.0'xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:templatematch='/'> <html> <body> <h2>MyCDCollection</h2> <tableborder='1'> <trbgcolor='#9acd32'> <thalign='left'>Title</th> <thalign='left'>Artist</th> </tr> <xsl:for-eachselect='catalog/cd'> <tr> <td><xsl:value-ofselect='title'/></td> <td><xsl:value-ofselect='artist'/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>"; stringresult=XslTransform(xml,xsl); Console.WriteLine(result); Console.Read(); } ///<summary> ///将Xml利用Xsl转换成目标xml ///</summary> ///<paramname="inputXmlConent">输入的xml</param> ///<paramname="inuptXslContent">xsl</param> ///<returns>转换后的目标xml</returns> staticStringXslTransform(stringinputXmlConent,stringinuptXslContent) { XmlReaderreaderXml=XmlReader.Create(newMemoryStream(UTF8Encoding.UTF8.GetBytes(inputXmlConent))); XmlReaderreaderXsl=XmlReader.Create(newMemoryStream(UTF8Encoding.UTF8.GetBytes(inuptXslContent))); XslCompiledTransformtransform=newXslCompiledTransform(); transform.Load(readerXsl); StringBuildersb=newStringBuilder(); XmlWriterSettingsSettings=newXmlWriterSettings() { Indent=true, ConformanceLevel=ConformanceLevel.Auto }; XmlWriterwriter=XmlWriter.Create(sb,Settings); transform.Transform(readerXml,writer); returnsb.ToString(); } } }
输出结果:
<html> <body> <h2>MyCDCollection</h2> <tableborder="1"> <trbgcolor="#9acd32"> <thalign="left">Title</th> <thalign="left">Artist</th> </tr> <tr> <td>EmpireBurlesque</td> <td>BobDylan</td> </tr> </table> </body> </html>
希望本文所述对大家C#程序设计有所帮助。