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类的更多相关文章

  1. 【HTML/XML 8】XSL,可扩展样式表语言

    导读:上篇博客说了在XML文档中实现表现形式的一种形式:CSS层叠样式表,本篇博客将接着说明其另一种实现方式XSL,并将分析XSL和CSS之间的 关系. 一.XSL简介 XSL(eXtensible ...

  2. CSS篇-样式表、选择器、权重、伪类

    CSS定义 CSS:Cascading Style Sheet(层叠样式表) // 写法 选择器 { 属性名: 属性值; } CSS样式表 (1)三种样式表使用 // 内联样式 <div sty ...

  3. CSS样式表及选择器相关内容(二)-伪类与伪元素选择器

    伪类与伪元素选择器归纳: 一.伪类选择器(伪类以":"开头,用在选择器后,用于指明元素在某种特殊的状态下才能被选中)    1.a标签伪类选择器,其他标签类似        eg: ...

  4. 使用 XSLT 作为 HTML 的样式表

    简介 当听到样式表这个词时,您可能会想到 CSS 样式表.XSLT 样式表通常用于 XML 转换,比如在 Web 服务之间映射数据.因为 XSLT 非常适合此用途,所以创建了顶层元素 <styl ...

  5. 微软BI 之SSIS 系列 - XML Task 中XSLT 样式表转换错误记录

    开篇介绍 此文章专门记录 XSLT 样式表转换过程中的语法问题 错误一 值与属性的倒置 修改了几次样式表,但还是一如既往的报错,报错信息如下: [XML Task] Error: An error o ...

  6. System.Web.Optimization对脚本和样式表的压缩操作

    1 是否允许样式表压缩 BundleTable.EnableOptimizations = true; 在MVC项目中的 BundleConfig操作中是微软已经给我们准备好的CSS和JS压缩,我们可 ...

  7. System.Web.Optimization对脚本和样式表的操作

    这个也是本章重点向描述的部分,首先我们可以使用VS2012RC来新建一个MVC4.0项目,版本可以为4.0或4.5.在Global.asax文件代码中,我们发现已经把过滤器,路由器,以及对样式表和脚本 ...

  8. 程序员接触新语言————hello world ^-^,web3种样式表

    我的第一个网页 <!DOCTYPE html> <html> <head lang="en"> <meta charset="U ...

  9. CSS样式----图文详解:css样式表和选择器

    主要内容 CSS概述 CSS和HTML结合的三种方式:行内样式表.内嵌样式表.外部样式表 CSS四种基本选择器:标签选择器.类选择器.ID选择器.通用选择器 CSS三种扩展选择器:组合选择器.后代选择 ...

随机推荐

  1. JavaFX窗体设置无边框

    public void start(Stage stage) throws Exception { longStart(); Parent root = FXMLLoader.load(getClas ...

  2. 死锁造成oom的排错

    1.死锁的查看步骤 jps -l jstack xxxx(xxxx为java进程的进程号) ------ 2:查看java进程的参数: jps -l jinfo -flag printGcDetial ...

  3. centos 用户组操作

    adduser testuser //新建testuser 用户 passwd testuser //给testuser 用户设置密码 useradd -g testgroup testuser // ...

  4. Nginx 系列教程

    Nginx(一):Nginx介绍 Nginx(二):编译安装Nginx及参数说明 Nginx(三):nginx.conf配置文件说明 [1] 配置参数说明 Nginx(三):nginx.conf配置文 ...

  5. Django基础十一之认证系统

    一 auth模块 我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统.此时我们需要实现包括用户注册.用户登录.用户认证.注销.修改密码等功能,这还真是个麻烦的事情呢. Django作为一个 ...

  6. Android--自定义Dialog style

    <style name="dialog" parent="@android:style/Theme.Dialog"> <item name=& ...

  7. fastjson<1.2.47 RCE 漏洞复现

    这两天爆出了 fastjson 的老洞,复现简单记录一下. 首先使用 spark 搭建一个简易的利用 fastjson 解析 json 的 http server. package cn.hackte ...

  8. FPS 游戏实现D3D透视

    FPS游戏可以说一直都比较热门,典型的代表有反恐精英,穿越火线,绝地求生等,基本上只要是FPS游戏都会有透视挂的存在,而透视挂还分为很多种类型,常见的有D3D透视,方框透视,还有一些比较高端的显卡透视 ...

  9. v8 引擎的内存

    一.nodejs查看内容使用情况: process.memoryUsage() 单位为 Btye 转化函数: var format = function(bytes) { return (bytes/ ...

  10. MacBook Pro 安装composer及Yii2.0

    最近想看看Yii的一些东西,需要安装一下composer curl -sS https://getcomposer.org/installer | php 此操作会下载最新版本到当前的目录下 然后将下 ...