首页 后端开发 XML/RSS教程 XSLT语法—在.net中使用XSLT转换xml文档的示例代码详解

XSLT语法—在.net中使用XSLT转换xml文档的示例代码详解

Mar 09, 2017 pm 04:59 PM

XSL即可扩展的样式表文件。 可以格式化xml的显示,也可以将xml转换成需要的另一种格式。

学习XSL必须熟悉XPath。XSL和XPath一样简单强大,容易学习。

1. XSL既然可以格式化xml的显示样式,我们先来看如何在xml中引用xsl文件

如下代码示例:

只需在xml文件的文档声明后面添加即可

2. XSL的格式

XSL也是一个标准的xml文件,它以xml文档声明开始,根元素必须是xsl:styleshee,同时根元素必须有version属性指定xsl的版本,和xmlns:xsl=” http://www.php.cn/”指定xsl命名空间,如下示例

3. Xsl要点 如下示例xml


<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet  type="text/xsl" href="pets-templates.xsl"?>
<pets>
  <pig color="blue" weight="100">
    <price>100</price>
    <desc>this is a blue pig</desc>
  </pig>
  <cat color="red" weight="9">
    <price>80</price>
    <desc>this is a red cat</desc>
  </cat>
  <dog color="green" weight="15">
    <price>80</price>
    <desc>this is a green dog</desc>
  </dog>
  <cat color="green" weight="15">
    <price>80</price>
    <desc>this is a green cat</desc>
  </cat>


  <dog color="blue" weight="10">
    <price>100</price>
    <desc>this is a blue dog</desc>
  </dog>
  <dog color="red" weight="9">
    <price>80</price>
    <desc>this is a red dog</desc>
  </dog>
</pets>
登录后复制

上面的xml在通过xsl格式化之后的显示效果如下:

1) xsl:template定义匹配节点的转换模板,属性match=”xpath expression”用来定义模板匹配的元素

如下定义匹配根节点的模板

<xsl:template match=”/”>
</xsl:template>
登录后复制

2) xsl:for-each循环显示select=”xpath expression”选择节点的转换 (类似编程语言中的foreach语句),

如下示例,选择了pets下面的子元素,并循环显示子元素的几点名字:

<xsl:for-each select=”/pets/*”>
<xsl:value-of select=”name()”/>
</xsl:for-each>
登录后复制

3) xsl:if 元素条件显示节点(类似编程语言中的if语句)注意小于号大于号要分别用<和>替代

<xsl:if test=”@weight &lt; 10”>
<i>its weight is less than 10 km</i>
</xsl:if>
登录后复制

4) xsl:choose 多分支条件显示 (类似编程语言中的switch语句)

<xsl:choose >
 <xsl:when test=”name() = ‘pig’”>
<i>this is a pig</i>
 </xsl:when>
<xsl:otherwise>
  <i>this is not a pig</i>
</xsl:otherwise>
</xsl:choose>
登录后复制

5) xsl:value-of 显示选择节点或者属性的值

选择子节点price

<xsl:value-of select=”pets/*/price”/>
登录后复制

选择属性weight

<xsl:value-of select=”pets/*/@weight”/>
登录后复制

6) xsl:attribute 构造xml节点的属性

用来向节点添加属性,例如:

<font>
<xsl:attribute name=”color”><xsl:value-of select=”pets/*/@color”/></xsl:attribute>
</font>
登录后复制

将输出

7) xsl:apply-templates 应用模板

如果xml文件结构比较复杂,可以定义多个template,然后使用标签应用模板,xsl:apply-templates 可以指定属性select=”xpath”来选择应用的模板,或者不指定select表示选择当前节点的模板。

请看下面示例xslt文件pets-templates.xsl

完整的示例xsl文件:pets.xsl


<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <head>
        <META http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>lovely pets</title>
        <style type="text/css">
          ul{margin:10px 0 10px 0;padding:0;width:400px;text-align:left;}
          li{height:60px;display:block;list-style:none;padding:4px;border:1px solid #f0f0f0;margin:5px;}
        </style>
      </head>
      <body>
        <center>
        <h1>lovely pets</h1>
        <ul>
          <xsl:for-each select="pets/*">
            <li>
              <img align="right">
                <xsl:choose>
                  <xsl:when test="name() = &#39;dog&#39;">
                    <xsl:attribute name="src">http://www.php.cn/;/xsl:attribute>
                  </xsl:when>
                  <xsl:when test="name() = &#39;pig&#39;">
                    <xsl:attribute name="src">http://www.php.cn/;/xsl:attribute>
                  </xsl:when>
                  <xsl:otherwise>
                    <xsl:attribute name="src">http://www.php.cn/@N00.jpg?1143660418</xsl:attribute>
                  </xsl:otherwise>
                </xsl:choose>
              </img>
              <font>
                <xsl:attribute name="face">Courier</xsl:attribute>
                <xsl:attribute name="color">
                  <xsl:value-of select="@color"/>
                </xsl:attribute>
                <xsl:value-of select="name()"/>
              </font> said: "<xsl:value-of select="desc"/>"
              weight:<xsl:value-of select="@weight"/>

              <xsl:if test="@weight < 10">
                <p>
                  <i>its weight is less than 10 km</i>
                </p>
              </xsl:if>


            </li>
          </xsl:for-each>
        </ul>
        </center>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
登录后复制

完整示例文件 pets-templates.xsl:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <head>
        <META http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>lovely pets</title>
        <style type="text/css">
          ul{margin:10px 0 10px 0;padding:0;width:400px;text-align:left;}
          li{height:60px;display:block;list-style:none;padding:4px;border:1px solid #f0f0f0;margin:5px;}
        </style>
      </head>
      <body>
        <center>
          <h1>lovely pets</h1>
          <ul>
            <xsl:apply-templates select="pets" />
          </ul>
        </center>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="pets">    
    <xsl:apply-templates select="dog"></xsl:apply-templates>
    <xsl:apply-templates select="pig"></xsl:apply-templates>
    <xsl:apply-templates select="cat"></xsl:apply-templates>
  </xsl:template>

  <xsl:template match="dog">
    <xsl:for-each select=".">
      <li>
        <img align="right">
          <xsl:attribute name="src">http://www.php.cn/;/xsl:attribute>          
        </img>
        <font>
          <xsl:attribute name="face">Courier</xsl:attribute>
          <xsl:attribute name="color">
            <xsl:value-of select="@color"/>
          </xsl:attribute>
          dog
        </font> said: "<xsl:value-of select="desc"/>"
        weight:<xsl:value-of select="@weight"/>

        <xsl:if test="@weight < 10">
          <p>
            <i>its weight is less than 10 km</i>
          </p>
        </xsl:if>
      </li>
    </xsl:for-each>
  </xsl:template>



  <xsl:template match="pig">
    <xsl:for-each select=".">
      <li>
        <img align="right">
          <xsl:attribute name="src">http://www.php.cn/;/xsl:attribute>
        </img>
        <font>
          <xsl:attribute name="face">Courier</xsl:attribute>
          <xsl:attribute name="color">
            <xsl:value-of select="@color"/>
          </xsl:attribute>
          pig
        </font> said: "<xsl:value-of select="desc"/>"
        weight:<xsl:value-of select="@weight"/>

        <xsl:if test="@weight < 10">
          <p>
            <i>its weight is less than 10 km</i>
          </p>
        </xsl:if>
      </li>
    </xsl:for-each>
  </xsl:template>


  <xsl:template match="cat">
    <xsl:for-each select=".">
      <li>
        <img align="right">
          <xsl:attribute name="src">http://www.php.cn/@N00.jpg?1143660418</xsl:attribute>
        </img>
        <font>
          <xsl:attribute name="face">Courier</xsl:attribute>
          <xsl:attribute name="color">
            <xsl:value-of select="@color"/>
          </xsl:attribute>
          cat
        </font> said: "<xsl:value-of select="desc"/>"
        weight:<xsl:value-of select="@weight"/>

        <xsl:if test="@weight < 10">
          <p>
            <i>its weight is less than 10 km</i>
          </p>
        </xsl:if>
      </li>
    </xsl:for-each>
  </xsl:template>
  
</xsl:stylesheet>
登录后复制

在c#.net中使用XslCompiledTransform转换xml文档,XslTransform也可以使用,但是这个类已经被微软标记为过时,最好不要再用了,如下代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace UseXslt
{
    class Program
    {
        static void Main(string[] args)
        {
            //声明XslTransform类实例
            System.Xml.Xsl.XslCompiledTransform trans = new System.Xml.Xsl.XslCompiledTransform();

            string xsltFile = @"X:\about.net\System.Xml\example\pets.xsl";
            using (StreamReader rdr = new StreamReader(xsltFile))
            {
                using (XmlReader xmlRdr = XmlReader.Create(rdr))
                {
                    //载入xsl文件
                    trans.Load(xmlRdr);
                }
            }
            string inputFile = @"X:\about.net\System.Xml\example\pets.xml";
            string outputFile = @"X:\about.net\System.Xml\example\pets-out.htm";
            //转化源文件输出到输出文件outputFile
            trans.Transform(inputFile, outputFile);
        }
    }
}
登录后复制


有一点需要注意,使用XslCompiledTransform转换出来的文件,是一个html格式的,这个类会自动在html的head标签中添加一个未关闭的meta标签 ;微软帮我们想的太多了。

Xslt还可以指定参数,定义变量,有关这些方面请查看相关文档。


以上是XSLT语法—在.net中使用XSLT转换xml文档的示例代码详解的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

能否用PowerPoint打开XML文件 能否用PowerPoint打开XML文件 Feb 19, 2024 pm 09:06 PM

XML文件可以用PPT打开吗?XML,即可扩展标记语言(ExtensibleMarkupLanguage),是一种被广泛应用于数据交换和数据存储的通用标记语言。与HTML相比,XML更加灵活,能够定义自己的标签和数据结构,使得数据的存储和交换更加方便和统一。而PPT,即PowerPoint,是微软公司开发的一种用于创建演示文稿的软件。它提供了图文并茂的方

Python中的XML数据转换为CSV格式 Python中的XML数据转换为CSV格式 Aug 11, 2023 pm 07:41 PM

Python中的XML数据转换为CSV格式XML(ExtensibleMarkupLanguage)是一种可扩展标记语言,常用于数据的存储和传输。而CSV(CommaSeparatedValues)则是一种以逗号分隔的文本文件格式,常用于数据的导入和导出。在处理数据时,有时需要将XML数据转换为CSV格式以便于分析和处理。Python作为一种功能强大

使用Python处理XML中的错误和异常 使用Python处理XML中的错误和异常 Aug 08, 2023 pm 12:25 PM

使用Python处理XML中的错误和异常XML是一种常用的数据格式,用于存储和表示结构化的数据。当我们使用Python处理XML时,有时可能会遇到一些错误和异常。在本篇文章中,我将介绍如何使用Python来处理XML中的错误和异常,并提供一些示例代码供参考。使用try-except语句捕获XML解析错误当我们使用Python解析XML时,有时候可能会遇到一些

Python解析XML中的特殊字符和转义序列 Python解析XML中的特殊字符和转义序列 Aug 08, 2023 pm 12:46 PM

Python解析XML中的特殊字符和转义序列XML(eXtensibleMarkupLanguage)是一种常用的数据交换格式,用于在不同系统之间传输和存储数据。在处理XML文件时,经常会遇到包含特殊字符和转义序列的情况,这可能会导致解析错误或者误解数据。因此,在使用Python解析XML文件时,我们需要了解如何处理这些特殊字符和转义序列。一、特殊字符和

C#开发中如何处理XML和JSON数据格式 C#开发中如何处理XML和JSON数据格式 Oct 09, 2023 pm 06:15 PM

C#开发中如何处理XML和JSON数据格式,需要具体代码示例在现代软件开发中,XML和JSON是广泛应用的两种数据格式。XML(可扩展标记语言)是一种用于存储和传输数据的标记语言,而JSON(JavaScript对象表示)是一种轻量级的数据交换格式。在C#开发中,我们经常需要处理和操作XML和JSON数据,本文将重点介绍如何使用C#处理这两种数据格式,并附上

C#的就业前景如何 C#的就业前景如何 Oct 19, 2023 am 11:02 AM

无论您是初学者还是有经验的专业人士,掌握C#将为您的职业发展铺平道路。

分享几个.NET开源的AI和LLM相关项目框架 分享几个.NET开源的AI和LLM相关项目框架 May 06, 2024 pm 04:43 PM

当今人工智能(AI)技术的发展如火如荼,它们在各个领域都展现出了巨大的潜力和影响力。今天大姚给大家分享4个.NET开源的AI模型LLM相关的项目框架,希望能为大家提供一些参考。https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel是一种开源的软件开发工具包(SDK),旨在将大型语言模型(LLM)如OpenAI、Azure

使用Python实现XML中的数据校验 使用Python实现XML中的数据校验 Aug 10, 2023 pm 01:37 PM

使用Python实现XML中的数据校验引言:在现实生活中,我们经常会处理各种各样的数据,其中XML(可扩展标记语言)是一种常用的数据格式。XML具有良好的可读性和可扩展性,被广泛应用于各种领域,如数据交换、配置文件等。在处理XML数据时,我们经常需要对数据进行校验,以确保数据的完整性和正确性。本文将介绍如何使用Python实现XML中的数据校验,并给出相应的

See all articles