C#使用XSLT实现xsl、xml与html相互转换

目录
  • 一、转为html文档
    • 1、xsl文件
    • 2、转换
    • 3、结果
  • 二、转为xml文档
    • 1、prices.xsl
    • 2、转换XsltArgumentList.AddExtensionObject
    • 3、结果
  • 三 、调用XSL参数
    • 1、xml文件
    • 2、order.xsl
    • 3、转换
  • 四、使用 XML 控件

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{

    private decimal newprice = 0;

    public decimal NewPriceFunc(decimal price, decimal conv){
       decimal tmp = price*conv;
       newprice = decimal.Round(tmp, 2);
       return newprice;
    }
  }
}

3、结果

output.xml

三 、调用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 转换后的结果:

ID="Xml1" runat="server" DocumentSource="DvdList.xml"    TransformSource="DvdList.xslt">

注意: 你也可以用编码中XmlDocument 对象赋给 Document 属性,或者把一个包含 XML 内容的字符串赋给 DocumentContent 属性,而不是使用 DocumentSource 属性。类似的,你可以一个 XslTransform 对象值赋给 Transform 属性来提供 XSLT 信息。

到此这篇关于C#使用XSLT实现xsl、xml与html相互转换的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • C#实现将文件转换为XML的方法

    本文实例讲述了C#实现将文件转换为XML的方法.分享给大家供大家参考,具体如下: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.IO; using System.Xml; namespace MyWindows { /// <summary> /// 这个示例演示如何把Offic

  • C#实现实体类和XML的相互转换

    一.实体类转换成XML 将实体类转换成XML需要使用XmlSerializer类的Serialize方法,将实体类序列化 public static string XmlSerialize<T>(T obj) { using (StringWriter sw = new StringWriter()) { Type t= obj.GetType(); XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.

  • C#实现实体类和XML相互转换

    一.实体类转换成XML 将实体类转换成XML需要使用XmlSerializer类的Serialize方法,将实体类序列化 public static string XmlSerialize<T>(T obj) { using (StringWriter sw = new StringWriter()) { Type t= obj.GetType(); XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.

  • C# XML字符串包含特殊字符的处理转换方法小结

    为了能正常输出XML格式的内容,必须要对不被XML允许的那些特殊字符进行转换.本文介绍的正是如何使用C#判断XML字符串是否含特殊字符并进行转换. 以下是几个特殊字符的对应实体. < < 小于号 > > 大于号 & & 和 &apos; ' 单引号 " " 双引号 在C#中,直接调用C#提供的方法,保存之后就会自动将特殊字符转为对应实体: string s =System.Security.SecurityElement.Escape(s

  • C#中使用JSON.NET实现JSON、XML相互转换

    官方 JSON.NET 地址 http://james.newtonking.com/pages/json-net.aspx XML TO JSON string xml = @"<?xml version=""1.0"" standalone=""no""?> <root> <person id=""1""> <name>Ala

  • C#实现XML与实体类之间相互转换的方法(序列化与反序列化)

    本文实例讲述了C#实现XML与实体类之间相互转换的方法.分享给大家供大家参考,具体如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Data; using System.Xml; using System.Xml.Serialization; /// <summary> /// Xml序列化与反序列化 //

  • C#对象与XMl文件之间的相互转换

    C#提供三种序列化方式,分别为:1.是使用BinaryFormatter进行串行化: 2.使用SoapFormatter进行串行化: 3.使用XmlSerializer进行串行化.其中对于BinaryFormatter的方式需要实现ISerializable接口,而XmlSeriializ不需要实现对应的接口,可以直接序列化.在这里面我们主要采用XMlSerialize来实现对应的序列化操作进而实现对应的对象和XMl文件之间的转换关系. 在通过序列化实现对应的转换关系操作的功能时,我首先创建了D

  • C# XML与Json之间相互转换实例详解

    对于这转换其实很简单,其中最重要的就是先要引用类库.可以到官网进行下载引用http://json.codeplex.com. XML转换为Json字符串 复制代码 代码如下: string xml = @"<?xml version=""1.0"" standalone=""no""?>                             <root>                   

  • C#使用XSLT实现xsl、xml与html相互转换

    目录 一.转为html文档 1.xsl文件 2.转换 3.结果 二.转为xml文档 1.prices.xsl 2.转换XsltArgumentList.AddExtensionObject 3.结果 三 .调用XSL参数 1.xml文件 2.order.xsl 3.转换 四.使用 XML 控件 XML文件 books.xml: <xml version="1.0" encoding="utf-8" ?> <bookstore> <boo

  • 一个用xslt样式将xml解析为xhtml的类TransformBinder(兼容FF和IE7.0)

    由于前面的方法xslt需要在xml文件内部直接导入,而项目中用到的xml文件是系统生成的,只能提供路径,而没有办法改写xml里面的内容,所以需要找一个方法能够在外部将xml和xslt关联在一起,这样既达到了目的,也可以应用于多个xml文件,方便管理. 先上代码,系统中使用module这个js进行打包,module这个工具是专门用来将js进行打包,这个工具以后的文章再做介绍,我自己现在只会使用,还没研究其底层的代码:这边我们将js写在一个文件里面,包括类以及类实现的方法, 下面是js代码:tran

  • XML+XSL+CSS+ASP打造留言簿

    前段时间无意间看到一个博客的RSS可以用XSL格式输出并且能在Firefox里浏览,想到自己以前写的一个XML留言簿因为不兼容Firefox所不了了之了,现在看到他的能在Firefox浏览就觉得很好奇,看了一下代码,一句一句的比对,最后终于找到了原因,也就把这个留言簿给完成了.因为是一个简单的XML留言簿,所以取名SXGB(Simple XML GuestBook). 留言本演示,管理密码为test:http://home.goofar.com/hotheart/gbook/gbook.asp

  • 如何快速通过XSL转换XML文件

    最近,我喜欢上了XML编程,但又苦于它的美观程度又不够,找了许多书才搞定. 用XML好是蛮好,但它还是不太适合做显示数据的语言.(比起HTML要查多了!)    XML文件作出来的东西看起来并不是那么美观,但还是可以找到补救的方法. XML可以只注重数据与文件格式的描述,而显示方面的工作就交给排版样式表.    排版样式表分:CSS和XSL.其中XSL非常适合XML.(在这里不讨论CSS!)    现在开始转换吧! XSL包含两大部分:XSLT和XSL Formatting Object XSL

  • 使用XSLT将XML数据转换成HTML

    使用一个简单的 XSL 样式表就可以将 XML 数据转换成 HTML.随着 XML 规范的不断演进,在新的版本中满足每个人的需要似乎已经成为必要:不幸的是,进行简单的转换一直都困扰着规范. 假设我有一个表示一个页面内容的 XML 数据,现在我想将其内容转换成布局.下面是我想要转换的 XML: <?xml version='1.0'?><?xml-stylesheet type="text/xsl" href="article.xsl"?>&l

  • 使用PHP和XSL stylesheets转换XML文档

    PHP是不少在Web开发领域奋战的勇士们所选用的武器,因为它是一种很直观的编程语言,有强大的函数,良好的跨平台兼容性,还有它是免费的.从网上的小商店到大型企业的网站都能看到PHP的影子. PHP有一点特性经常被人们忽视,那就是和XSL stylesheets合作对XML进行解析的能力.下面就让我们来看看怎样在PHP中设置一个XSL解析器以及你该如何使用这一功能. 例子列表A是一个简单的订单文档,我们会将这个文档输入XSL解析器.同时,列表B中的XSL stylesheet也会被输入XSL解析器.

  • ASP.NET使用xslt将xml转换成Excel

    序: 最近在给客户做一个管理系统的时候,客户提出要将查询结果导出到Excel.对于还是实习生的我倍感压力,于是找了点资料.网上有个示例,其中方法十分简单.于是照猫画虎,把方法和心得与大家分享.OK,Let`s go 第一步: 创建一个Excel文件(就是 普通的Excel),在第一个单元格输入"city",然后选择"另存为",此时弹出保存窗口.注意:将保持格式选择为"XML 表格(*.xml)",点击保存.完毕后用记事本打开这个Excel文件.你

  • Jsp结合XML+XSLT将输出转换为Html格式

    我们知道 XML+XSLT就可以直接输出到支持XML的浏览器上,如IE 5.0以上,但是,我们还要考虑到有不少浏览器不直接支持XML,在这种情况下,我们需要在服务器上进行转换成html输出到浏览器,这种临时过渡办法恐怕要在一段时间内一直要使用. 使用Jsp 加上tablib标识库,我们可以完成这种转换. 著名open source项目组jakarta.apache.org推出的系列标识库中,就有这个功能的tanglib:http://jakarta.apache.org/taglibs/doc/

  • XML基本概念XPath、XSLT与XQuery函数介绍

    目录 一.XPath查询 1.选取节点 2.谓语(Predicates) 3.选取未知节点 4.选取若干路径 5.XPath 轴(Axes) 6.XPath 运算符 二.XSLT 1.样式表声明 2.创建 XSL 样式表 3.把 XSL 样式表链接到 XML 文档 4.XSL元素 三.XQuery 1.XQuery 的基础语法规则: 2.FLWOR 表达式 一.XPath查询 XSL指扩展样式表语言(EXtensible Stylesheet Language). 官方网站:https://ww

  • 使用XSL将XML文档中的CDATA注释输出为HTML文本

    要利用DOM 来存取XML 文件,你必须将XML 文件连结到HTML 网页上. 示例代码 1. test.xml <?xml version="1.0" encoding="gb2312"?><?xml-stylesheet href="test.xsl" type="text/xsl"?><entry><title>entry with images</title>

随机推荐