Home Backend Development XML/RSS Tutorial XSLT syntax—detailed explanation of sample code for using XSLT to convert xml documents in .net

XSLT syntax—detailed explanation of sample code for using XSLT to convert xml documents in .net

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>
Copy after login

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

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

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

<xsl:template match=”/”>
</xsl:template>
Copy after login

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

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

<xsl:for-each select=”/pets/*”>
<xsl:value-of select=”name()”/>
</xsl:for-each>
Copy after login

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

<xsl:if test=”@weight &lt; 10”>
<i>its weight is less than 10 km</i>
</xsl:if>
Copy after login

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>
Copy after login

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

选择子节点price

<xsl:value-of select=”pets/*/price”/>
Copy after login

选择属性weight

<xsl:value-of select=”pets/*/@weight”/>
Copy after login

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

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

<font>
<xsl:attribute name=”color”><xsl:value-of select=”pets/*/@color”/></xsl:attribute>
</font>
Copy after login

将输出

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>
Copy after login

完整示例文件 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>
Copy after login

在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);
        }
    }
}
Copy after login


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

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


The above is the detailed content of XSLT syntax—detailed explanation of sample code for using XSLT to convert xml documents in .net. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Convert XML data to CSV format in Python Convert XML data to CSV format in Python Aug 11, 2023 pm 07:41 PM

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Handling errors and exceptions in XML using Python Handling errors and exceptions in XML using Python Aug 08, 2023 pm 12:25 PM

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Python parsing special characters and escape sequences in XML Python parsing special characters and escape sequences in XML Aug 08, 2023 pm 12:46 PM

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

What are the employment prospects of C#? What are the employment prospects of C#? Oct 19, 2023 am 11:02 AM

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

Using Python to implement data verification in XML Using Python to implement data verification in XML Aug 10, 2023 pm 01:37 PM

Using Python to implement data validation in XML Introduction: In real life, we often deal with a variety of data, among which XML (Extensible Markup Language) is a commonly used data format. XML has good readability and scalability, and is widely used in various fields, such as data exchange, configuration files, etc. When processing XML data, we often need to verify the data to ensure the integrity and correctness of the data. This article will introduce how to use Python to implement data verification in XML and give the corresponding

See all articles