XSLT可扩展样式表语言转换 System.Xml.Xsl、XslCompiledTransform类
XML文件
books.xml:
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
  <book genre="autobiography" publicationdate="1991" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>
转为html文档
1、xsl文件
books.xsl:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<HTML>
    <head>
        <title>Price List</title>
    </head>
<body>
    <table>
        <xsl:apply-templates/>
    </table>
</body>
</HTML>
</xsl:template>
<xsl:template match="bookstore">
    <xsl:apply-templates select="book"/>
</xsl:template>
<xsl:template match="book">
    <tr>
        <td>
            <xsl:value-of select="title"/>
        </td>
        <td>
            <xsl:value-of select="price"/>
        </td>
    </tr>
</xsl:template>
</xsl:stylesheet>
2、转换
将books.xml按照books.xsl定义的格式转换成out.html
XslCompiledTransform trans = new XslCompiledTransform(); trans.Load(@"..\..\books.xsl"); trans.Transform(@"..\..\books.xml", "out.html");
3、结果
out.html:
<HTML>
  <head>
    <META http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Price List</title>
  </head>
  <body>
    <table>
      <tr>
        <td>The Autobiography of Benjamin Franklin</td>
        <td>8.99</td>
      </tr>
      <tr>
        <td>The Confidence Man</td>
        <td>11.99</td>
      </tr>
      <tr>
        <td>The Gorgias</td>
        <td>9.99</td>
      </tr>
    </table>
  </body>
</HTML>
转为xml文档
1、prices.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myObj="urn:price-conv">
<!--Price conversion factor-->
<xsl:param name="conv" select="1.15"/>
  <xsl:template match="bookstore">
  <bookstore>
  <xsl:for-each select="book">
    <book>
    <xsl:copy-of select="node()"/>
       <new-price>
          <xsl:value-of select="myObj:NewPriceFunc(./price, $conv)"/>
       </new-price>
    </book>
  </xsl:for-each>
  </bookstore>
  </xsl:template>
</xsl:stylesheet>
2、转换XsltArgumentList.AddExtensionObject
在以下示例中,样式表使用 XSLT 扩展对象要转换的书籍价格。
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
public class Sample {
   public static void Main() {
    // Create the XslCompiledTransform and load the stylesheet.
    XslCompiledTransform xslt = new XslCompiledTransform();
    xslt.Load("prices.xsl");
    // Create an XsltArgumentList.
    XsltArgumentList xslArg = new XsltArgumentList();
    // Add an object to calculate the new book price.
    BookPrice obj = new BookPrice();
    xslArg.AddExtensionObject("urn:price-conv", obj);
    using (XmlWriter w = XmlWriter.Create("output.xml"))
    {
        // Transform the file.
        xslt.Transform("books.xml", xslArg, w);
    }
  }
  // Convert the book price to a new price using the conversion factor.
  public class BookPrice{
    ;
    public decimal NewPriceFunc(decimal price, decimal conv){
       decimal tmp = price*conv;
       newprice = );
       return newprice;
    }
  }
}
3、结果
prices.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myObj="urn:price-conv">
<!--Price conversion factor-->
<xsl:param name="conv" select="1.15"/>
  <xsl:template match="bookstore">
  <bookstore>
  <xsl:for-each select="book">
    <book>
    <xsl:copy-of select="node()"/>
       <new-price>
          <xsl:value-of select="myObj:NewPriceFunc(./price, $conv)"/>
       </new-price>
    </book>
  </xsl:for-each>
  </bookstore>
  </xsl:template>
</xsl:stylesheet>
调用XSL参数
1、xml文件
order.xml
<!--Represents a customer order-->
<order>
  <book ISBN='10-861003-324'>
    <title>The Handmaid's Tale</title>
    <price>19.95</price>
  </book>
  <cd ISBN='2-3631-4'>
    <title>Americana</title>
    <price>16.95</price>
  </cd>
</order>
2、order.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:param name="date"/>
  <xsl:template match="/">
    <order>
      <date><xsl:value-of select="$date"/></date>
      <total><xsl:value-of select="sum(//price)"/></total>
    </order>
  </xsl:template>
</xsl:stylesheet>
3、转换
下面的示例使用AddParam方法来创建表示当前日期和时间的参数。
using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
public class Sample
{
    public static void Main()
    {
        // Create the XslCompiledTransform and load the stylesheet.
        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load("order.xsl");
        // Create the XsltArgumentList.
        XsltArgumentList xslArg = new XsltArgumentList();
        // Create a parameter which represents the current date and time.
        DateTime d = DateTime.Now;
        xslArg.AddParam("date", "", d.ToString());
        // Transform the file.
        using (XmlWriter w = XmlWriter.Create("output.xml"))
        {
            xslt.Transform("order.xml", xslArg, w);
        }
    }
}
使用 XML 控件
有时候你可能希望把带有其他内容的转换后的 HTML 输出和 Web 控件组合在一起,XML 控件在页面独立的部分显示 XSL 转换后的结果:
<asp:Xml ID="Xml1" runat="server" DocumentSource="DvdList.xml" TransformSource="DvdList.xslt"></asp:Xml>
这个示例最好的一点是只需设置 2 个属性而不需要手工书写任何代码。
不必为了使用 XML 控件而使用独立的文件。
你也可以在编码中把 XmlDocument 对象赋给 Document 属性,或者把一个包含 XML 内容的字符串赋给 DocumentContent 属性,而不是使用 DocumentSource 属性。类似的,你可以一个 XslTransform 对象值赋给 Transform 属性来提供 XSLT 信息。
如果需要编程来支持 XML 和 XSLT 数据(从数据库记录中抽取数据),这些技术将非常有用。
使用 LINQ to XML 转换 XML
XSL 并不是改变 XML 格式的唯一方式(过去它是唯一实际可行的办法),但今天,LINQ to XML 提供了一个富有竞争力的选择。要使用 LINQ to XML 进行转换,你需要一个运用投影的 LINQ 表达式。技巧在于投影必须返回一个 XElement 而不是匿名类型。
string xmlFile = Server.MapPath("DvdList.xml");
XDocument doc = XDocument.Load(xmlFile);
XDocument newDoc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Movies",
        from DVD in doc.Descendants("DVD")
        select new XElement[]
        {
            new XElement ("Moive",
                new XAttribute("name", (string)DVD.Element("Title")),
                DVD.Descendants("Star")
            )
        }
    )
);
string newFile = Server.MapPath("MovieList.xml");
newDoc.Save(newFile);
结果:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Movies>
  <Moive name="The Matrix">
    <Star>Keanu Reeves</Star>
    <Star>Laurence Fishburne</Star>
  </Moive>
  <Moive name="Forrest Gump">
    <Star>Tom Hanks</Star>
    <Star>Robin Wright</Star>
  </Moive>
</Movies>
基于 LINQ 转换的语法通常要比使用 XSL 样式表的转换更容易理解,并且更加精确。你也可以很方便的替换为另一个 IEnumable<T>的集合,包括 LINQ to Entities 获得的结果集,然后随意打包成另一种格式的 XML 文档。
XSLT可扩展样式表语言转换 System.Xml.Xsl、XslCompiledTransform类的更多相关文章
- 【HTML/XML 8】XSL,可扩展样式表语言
		
导读:上篇博客说了在XML文档中实现表现形式的一种形式:CSS层叠样式表,本篇博客将接着说明其另一种实现方式XSL,并将分析XSL和CSS之间的 关系. 一.XSL简介 XSL(eXtensible ...
 - CSS篇-样式表、选择器、权重、伪类
		
CSS定义 CSS:Cascading Style Sheet(层叠样式表) // 写法 选择器 { 属性名: 属性值; } CSS样式表 (1)三种样式表使用 // 内联样式 <div sty ...
 - CSS样式表及选择器相关内容(二)-伪类与伪元素选择器
		
伪类与伪元素选择器归纳: 一.伪类选择器(伪类以":"开头,用在选择器后,用于指明元素在某种特殊的状态下才能被选中) 1.a标签伪类选择器,其他标签类似 eg: ...
 - 使用 XSLT 作为 HTML 的样式表
		
简介 当听到样式表这个词时,您可能会想到 CSS 样式表.XSLT 样式表通常用于 XML 转换,比如在 Web 服务之间映射数据.因为 XSLT 非常适合此用途,所以创建了顶层元素 <styl ...
 - 微软BI 之SSIS 系列 - XML Task 中XSLT 样式表转换错误记录
		
开篇介绍 此文章专门记录 XSLT 样式表转换过程中的语法问题 错误一 值与属性的倒置 修改了几次样式表,但还是一如既往的报错,报错信息如下: [XML Task] Error: An error o ...
 - System.Web.Optimization对脚本和样式表的压缩操作
		
1 是否允许样式表压缩 BundleTable.EnableOptimizations = true; 在MVC项目中的 BundleConfig操作中是微软已经给我们准备好的CSS和JS压缩,我们可 ...
 - System.Web.Optimization对脚本和样式表的操作
		
这个也是本章重点向描述的部分,首先我们可以使用VS2012RC来新建一个MVC4.0项目,版本可以为4.0或4.5.在Global.asax文件代码中,我们发现已经把过滤器,路由器,以及对样式表和脚本 ...
 - 程序员接触新语言————hello world ^-^,web3种样式表
		
我的第一个网页 <!DOCTYPE html> <html> <head lang="en"> <meta charset="U ...
 - CSS样式----图文详解:css样式表和选择器
		
主要内容 CSS概述 CSS和HTML结合的三种方式:行内样式表.内嵌样式表.外部样式表 CSS四种基本选择器:标签选择器.类选择器.ID选择器.通用选择器 CSS三种扩展选择器:组合选择器.后代选择 ...
 
随机推荐
- 【bcrypt】vue项目中bcrypt安装报错
			
[报错] 报错时安装方法: npm install bcrypt [解决方法] npm install bcryptjs 用 bcryptjs 替换 bcrypt 即可.
 - Spring bean加载之1:BeanFactory和FactoryBean
			
BeanFactory BeanFactory:以Factory结尾,表示它是一个工厂类(接口),用于管理Bean的一个工厂.在Spring中,BeanFactory是IOC容器的核心接口,它的职责包 ...
 - 用jquery和php实现ajax异步请求响应
			
ajax技术可以实现异步请求和响应,下面的是用jquery向一个php脚本发送异步请求,并得到响应. 第一步,准备好前台的html表单,和jquery实现的ajax请求 <html lang=& ...
 - golang使用一个二叉树来实现一个插入排序
			
思路不太好理解,请用断点 package main import "fmt" type tree struct { value int left, right *tree } fu ...
 - [Done] Codeforces Round #562 (Div. 2) 题解
			
A - Circle Metro 模拟几百步就可以了. B - Pairs 爆搜一下,时间复杂度大概是 $O(4 * n)$ Code: 56306723 C - Increasing by Modu ...
 - glance
			
第二篇glance— 镜像服务 一.glance介绍: Glance是Openstack项目中负责镜像管理的模块,其功能包括虚拟机镜像的查找.注册和检索等. Glance提供 ...
 - vue的jsonp百度下拉菜单
			
通过vue的jsonp实现百度下拉菜单的请求,vue的版本是2.9.2 <!DOCTYPE html> <html lang="en"> <head& ...
 - 【MySQL】数据库(分库分表)中间件对比
			
分区:对业务透明,分区只不过把存放数据的文件分成了许多小块,例如mysql中的一张表对应三个文件.MYD,MYI,frm. 根据一定的规则把数据文件(MYD)和索引文件(MYI)进行了分割,分区后的表 ...
 - 【转载】IIS一个网站如何绑定多个主机域名
			
在IIS Web服务器的网站配置的过程中,有时候需要一个网站配置对应多个域名记录,例如不带www的主域名以及带www的域名解析记录对应同一个网站文件,此时最简单的配置方法就是将一个网站绑定多个主机域名 ...
 - SAP云平台上的ABAP编程环境里如何消费第三方服务
			
在ABAP On-Premises环境下,使用ABAP编程消费第三方服务,相信很多ABAP顾问都已经非常熟悉了,无非就是使用CL_HTTP_CLIENT或者CL_REST_HTTP_CLIENT来发送 ...