search
HomeBackend DevelopmentXML/RSS TutorialXSLT syntax—detailed explanation of sample code for using XSLT to convert xml documents in .net

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语句)注意小于号大于号要分别用67bffed8d39c986beaddeed3e8cd5568替代

<xsl:if test=”@weight < 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 id="lovely-nbsp-pets">lovely pets</h1>
        <ul>
          <xsl:for-each select="pets/*">
            <li>
              <img  align="right" alt="XSLT syntax—detailed explanation of sample code for using XSLT to convert xml documents in .net" >
                <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 id="lovely-nbsp-pets">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" alt="XSLT syntax—detailed explanation of sample code for using XSLT to convert xml documents in .net" >
          <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" alt="XSLT syntax—detailed explanation of sample code for using XSLT to convert xml documents in .net" >
          <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" alt="XSLT syntax—detailed explanation of sample code for using XSLT to convert xml documents in .net" >
          <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还可以指定参数,定义变量,有关这些方面请查看相关文档。


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
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
Scaling XML/RSS Processing: Performance Optimization TechniquesScaling XML/RSS Processing: Performance Optimization TechniquesApr 27, 2025 am 12:28 AM

When processing XML and RSS data, you can optimize performance through the following steps: 1) Use efficient parsers such as lxml to improve parsing speed; 2) Use SAX parsers to reduce memory usage; 3) Use XPath expressions to improve data extraction efficiency; 4) implement multi-process parallel processing to improve processing speed.

RSS Document Formats: Exploring RSS 2.0 and BeyondRSS Document Formats: Exploring RSS 2.0 and BeyondApr 26, 2025 am 12:22 AM

RSS2.0 is an open standard that allows content publishers to distribute content in a structured way. It contains rich metadata such as titles, links, descriptions, release dates, etc., allowing subscribers to quickly browse and access content. The advantages of RSS2.0 are its simplicity and scalability. For example, it allows custom elements, which means developers can add additional information based on their needs, such as authors, categories, etc.

Understanding RSS: An XML PerspectiveUnderstanding RSS: An XML PerspectiveApr 25, 2025 am 12:14 AM

RSS is an XML-based format used to publish frequently updated content. 1. RSSfeed organizes information through XML structure, including title, link, description, etc. 2. Creating RSSfeed requires writing in XML structure, adding metadata such as language and release date. 3. Advanced usage can include multimedia files and classified information. 4. Use XML verification tools during debugging to ensure that the required elements exist and are encoded correctly. 5. Optimizing RSSfeed can be achieved by paging, caching and keeping the structure simple. By understanding and applying this knowledge, content can be effectively managed and distributed.

RSS in XML: Decoding Tags, Attributes, and StructureRSS in XML: Decoding Tags, Attributes, and StructureApr 24, 2025 am 12:09 AM

RSS is an XML-based format used to publish and subscribe to content. The XML structure of an RSS file includes a root element, an element, and multiple elements, each representing a content entry. Read and parse RSS files through XML parser, and users can subscribe and get the latest content.

XML's Advantages in RSS: A Technical Deep DiveXML's Advantages in RSS: A Technical Deep DiveApr 23, 2025 am 12:02 AM

XML has the advantages of structured data, scalability, cross-platform compatibility and parsing verification in RSS. 1) Structured data ensures consistency and reliability of content; 2) Scalability allows the addition of custom tags to suit content needs; 3) Cross-platform compatibility makes it work seamlessly on different devices; 4) Analytical and verification tools ensure the quality and integrity of the feed.

RSS in XML: Unveiling the Core of Content SyndicationRSS in XML: Unveiling the Core of Content SyndicationApr 22, 2025 am 12:08 AM

The implementation of RSS in XML is to organize content through a structured XML format. 1) RSS uses XML as the data exchange format, including elements such as channel information and project list. 2) When generating RSS files, content must be organized according to specifications and published to the server for subscription. 3) RSS files can be subscribed through a reader or plug-in to automatically update the content.

Beyond the Basics: Advanced RSS Document FeaturesBeyond the Basics: Advanced RSS Document FeaturesApr 21, 2025 am 12:03 AM

Advanced features of RSS include content namespaces, extension modules, and conditional subscriptions. 1) Content namespace extends RSS functionality, 2) Extended modules such as DublinCore or iTunes to add metadata, 3) Conditional subscription filters entries based on specific conditions. These functions are implemented by adding XML elements and attributes to improve information acquisition efficiency.

The XML Backbone: How RSS Feeds are StructuredThe XML Backbone: How RSS Feeds are StructuredApr 20, 2025 am 12:02 AM

RSSfeedsuseXMLtostructurecontentupdates.1)XMLprovidesahierarchicalstructurefordata.2)Theelementdefinesthefeed'sidentityandcontainselements.3)elementsrepresentindividualcontentpieces.4)RSSisextensible,allowingcustomelements.5)Bestpracticesincludeusing

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft