亲宝软件园·资讯

展开

C#实现XSL转换 C#实现XSL转换的方法

Jimmy.Yang 人气:0
想了解C#实现XSL转换的方法的相关内容吗,Jimmy.Yang在本文为您仔细讲解C#实现XSL转换的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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#程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论