C#完成XSL轉換的辦法。本站提示廣大學習愛好者:(C#完成XSL轉換的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成XSL轉換的辦法正文
本文實例講述了C#完成XSL轉換的辦法。分享給年夜家供年夜家參考,詳細以下:
xsl 可便利的將一種格局的xml,轉換成另外一種格局的xml,參考上面的代碼:
using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Xsl; namespace XslLoad { class Program { static void Main(string[] args) { string xml = @"<?xml version='1.0' encoding='ISO-8859-1'?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> </catalog>"; string xsl = @"<?xml version='1.0' encoding='ISO-8859-1'?> <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:template match='/'> <html> <body> <h2>My CD Collection</h2> <table border='1'> <tr bgcolor='#9acd32'> <th align='left'>Title</th> <th align='left'>Artist</th> </tr> <xsl:for-each select='catalog/cd'> <tr> <td><xsl:value-of select='title'/></td> <td><xsl:value-of select='artist'/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>"; string result = XslTransform(xml, xsl); Console.WriteLine(result); Console.Read(); } /// <summary> /// 將Xml應用Xsl轉換成目的xml /// </summary> /// <param name="inputXmlConent">輸出的xml</param> /// <param name="inuptXslContent">xsl</param> /// <returns>轉換後的目的xml</returns> static String XslTransform(string inputXmlConent, string inuptXslContent) { XmlReader readerXml = XmlReader.Create(new MemoryStream(UTF8Encoding.UTF8.GetBytes(inputXmlConent))); XmlReader readerXsl = XmlReader.Create(new MemoryStream(UTF8Encoding.UTF8.GetBytes(inuptXslContent))); XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(readerXsl); StringBuilder sb = new StringBuilder(); XmlWriterSettings Settings = new XmlWriterSettings() { Indent = true, ConformanceLevel = ConformanceLevel.Auto }; XmlWriter writer = XmlWriter.Create(sb, Settings); transform.Transform(readerXml, writer); return sb.ToString(); } } }
輸入成果:
<html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th align="left">Title</th> <th align="left">Artist</th> </tr> <tr> <td>Empire Burlesque</td> <td>Bob Dylan</td> </tr> </table> </body> </html>
願望本文所述對年夜家C#法式設計有所贊助。