简体中文 繁體中文 English Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français Japanese

站内搜索

搜索

活动公告

通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,将及时处理!
10-23 09:31

掌握XSLT技巧轻松实现XML数据格式化与转换从基础语法到实际应用全面解析XML文档样式表处理方法

SunJu_FaceMall

3万

主题

153

科技点

3万

积分

大区版主

碾压王

积分
32103
发表于 2025-9-17 19:30:06 | 显示全部楼层 |阅读模式 [标记阅至此楼]

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

XSLT(Extensible Stylesheet Language Transformations)是一种用于将XML文档转换为其他格式的强大语言。在当今数据交换和文档处理领域,XML作为一种通用的数据格式被广泛应用,而XSLT则提供了处理和转换这些XML数据的灵活方法。无论是将XML转换为HTML用于网页显示,还是转换为其他XML格式以满足不同系统的需求,XSLT都扮演着至关重要的角色。

本文将全面介绍XSLT的基础语法、核心概念以及实际应用技巧,帮助读者掌握这一强大的技术,轻松实现XML数据的格式化与转换。通过丰富的示例和详细的解释,即使是初学者也能逐步理解并应用XSLT解决实际问题。

XSLT基础概念

什么是XSLT

XSLT是W3C推荐的一种标准,它属于XSL(Extensible Stylesheet Language)家族的一部分。XSLT的主要功能是将XML文档转换为其他格式的文档,如HTML、XML、文本或其他格式。这种转换是通过应用一系列模板规则来实现的,这些规则定义了如何处理源XML文档中的各个部分。

XSLT与XML的关系

XML(eXtensible Markup Language)是一种用于存储和传输数据的标记语言,它具有自描述性和平台无关性的特点。然而,XML本身只关注数据的结构和内容,而不涉及数据的显示和格式。这就是XSLT发挥作用的地方——它能够读取XML数据,并根据预定义的规则将其转换为所需的格式。

一个典型的XSLT处理过程包括三个主要组件:

1. 源XML文档:包含需要转换的数据
2. XSLT样式表:包含转换规则和模板
3. 结果文档:转换后的输出

XSLT处理器

XSLT处理器是执行XSLT转换的软件组件。它读取源XML文档和XSLT样式表,应用样式表中定义的规则,生成结果文档。常见的XSLT处理器包括:

• Saxon:功能强大的Java实现的XSLT处理器
• Xalan:Apache软件基金会的XSLT处理器
• MSXML:微软的XML处理器,内置在Windows和Internet Explorer中
• libxslt:开源的XSLT处理器,是GNOME项目的一部分

XSLT基础语法

XSLT文档结构

一个基本的XSLT文档结构如下:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  3.     <!-- XSLT模板和规则在这里定义 -->
  4. </xsl:stylesheet>
复制代码

或者使用XSLT 2.0或更高版本:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  3.     <!-- XSLT模板和规则在这里定义 -->
  4. </xsl:stylesheet>
复制代码

模板规则

模板是XSLT的核心概念,它定义了如何处理XML文档中的特定节点。基本的模板语法如下:
  1. <xsl:template match="pattern">
  2.     <!-- 模板内容 -->
  3. </xsl:template>
复制代码

其中,match属性指定了该模板应用的XML节点模式。例如:
  1. <xsl:template match="/">
  2.     <!-- 处理文档根节点的模板 -->
  3. </xsl:template>
  4. <xsl:template match="book">
  5.     <!-- 处理book元素的模板 -->
  6. </xsl:template>
复制代码

XPath表达式

XPath是用于在XML文档中定位节点的语言,它在XSLT中扮演着重要角色。通过XPath,我们可以选择XML文档中的特定节点或节点集。以下是一些常用的XPath表达式示例:

• /:选择文档根节点
• *:选择所有元素节点
• @*:选择所有属性节点
• node():选择所有节点(元素、文本、注释、处理指令等)
• text():选择文本节点
• .:选择当前节点
• ..:选择当前节点的父节点
• //:选择文档中所有匹配的节点,无论它们在什么位置
• book:选择所有book元素
• book/title:选择所有book元素的子元素title
• book[@id]:选择所有具有id属性的book元素
• book[@id='bk101']:选择id属性值为’bk101’的book元素

输出指令

XSLT允许我们通过xsl:output指令指定输出文档的格式和属性:
  1. <xsl:output method="xml" indent="yes" encoding="UTF-8"/>
复制代码

常用的method属性值包括:

• xml:输出为XML格式(默认)
• html:输出为HTML格式
• text:输出为纯文本格式

XSLT核心元素详解

xsl:template

xsl:template是XSLT中最基本的元素,用于定义处理特定节点的模板规则。它的match属性指定了该模板应用的节点模式。

示例:
  1. <xsl:template match="/">
  2.     <html>
  3.         <body>
  4.             <h1>Book List</h1>
  5.             <xsl:apply-templates select="catalog/book"/>
  6.         </body>
  7.     </html>
  8. </xsl:template>
  9. <xsl:template match="book">
  10.     <div>
  11.         <h2><xsl:value-of select="title"/></h2>
  12.         <p>Author: <xsl:value-of select="author"/></p>
  13.         <p>Price: <xsl:value-of select="price"/></p>
  14.     </div>
  15. </xsl:template>
复制代码

xsl:value-of

xsl:value-of用于提取并输出选定节点的值。它的select属性指定要提取的节点。

示例:
  1. <xsl:template match="book">
  2.     <p>Title: <xsl:value-of select="title"/></p>
  3.     <p>Author: <xsl:value-of select="author"/></p>
  4. </xsl:template>
复制代码

xsl:for-each

xsl:for-each用于循环处理节点集中的每个节点。它的select属性指定要循环的节点集。

示例:
  1. <xsl:template match="/">
  2.     <ul>
  3.         <xsl:for-each select="catalog/book">
  4.             <li><xsl:value-of select="title"/> by <xsl:value-of select="author"/></li>
  5.         </xsl:for-each>
  6.     </ul>
  7. </xsl:template>
复制代码

xsl:if

xsl:if用于条件处理,当指定的条件为真时,执行其内容。它的test属性指定要测试的条件。

示例:
  1. <xsl:template match="book">
  2.     <div>
  3.         <h2><xsl:value-of select="title"/></h2>
  4.         <xsl:if test="price > 50">
  5.             <p class="expensive">This book is expensive!</p>
  6.         </xsl:if>
  7.     </div>
  8. </xsl:template>
复制代码

xsl:choose, xsl:when, xsl:otherwise

这组元素用于多条件判断,类似于编程语言中的switch-case语句。

示例:
  1. <xsl:template match="book">
  2.     <div>
  3.         <h2><xsl:value-of select="title"/></h2>
  4.         <xsl:choose>
  5.             <xsl:when test="price < 20">
  6.                 <p class="cheap">This book is cheap!</p>
  7.             </xsl:when>
  8.             <xsl:when test="price >= 20 and price <= 50">
  9.                 <p class="moderate">This book is moderately priced.</p>
  10.             </xsl:when>
  11.             <xsl:otherwise>
  12.                 <p class="expensive">This book is expensive!</p>
  13.             </xsl:otherwise>
  14.         </xsl:choose>
  15.     </div>
  16. </xsl:template>
复制代码

xsl:sort

xsl:sort用于在xsl:for-each或xsl:apply-templates中对节点进行排序。

示例:
  1. <xsl:template match="/">
  2.     <ul>
  3.         <xsl:for-each select="catalog/book">
  4.             <xsl:sort select="title" order="ascending"/>
  5.             <li><xsl:value-of select="title"/> by <xsl:value-of select="author"/></li>
  6.         </xsl:for-each>
  7.     </ul>
  8. </xsl:template>
复制代码

xsl:variable 和 xsl:param

xsl:variable用于定义变量,xsl:param用于定义参数。变量一旦定义就不能更改,而参数可以在模板调用时传递值。

示例:
  1. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2.     <xsl:variable name="currency" select="'USD'"/>
  3.    
  4.     <xsl:template match="/">
  5.         <xsl:apply-templates select="catalog/book">
  6.             <xsl:with-param name="discount" select="0.1"/>
  7.         </xsl:apply-templates>
  8.     </xsl:template>
  9.    
  10.     <xsl:template match="book">
  11.         <xsl:param name="discount" select="0"/>
  12.         <div>
  13.             <h2><xsl:value-of select="title"/></h2>
  14.             <p>Price: <xsl:value-of select="price * (1 - $discount)"/> <xsl:value-of select="$currency"/></p>
  15.         </div>
  16.     </xsl:template>
  17. </xsl:stylesheet>
复制代码

xsl:apply-templates

xsl:apply-templates用于指示XSLT处理器应用其他模板来处理当前节点的子节点。它的select属性指定要处理的节点集。

示例:
  1. <xsl:template match="/">
  2.     <html>
  3.         <body>
  4.             <h1>Book List</h1>
  5.             <xsl:apply-templates select="catalog/book"/>
  6.         </body>
  7.     </html>
  8. </xsl:template>
  9. <xsl:template match="book">
  10.     <div>
  11.         <xsl:apply-templates select="title"/>
  12.         <xsl:apply-templates select="author"/>
  13.         <xsl:apply-templates select="price"/>
  14.     </div>
  15. </xsl:template>
  16. <xsl:template match="title">
  17.     <h2><xsl:value-of select="."/></h2>
  18. </xsl:template>
  19. <xsl:template match="author">
  20.     <p>Author: <xsl:value-of select="."/></p>
  21. </xsl:template>
  22. <xsl:template match="price">
  23.     <p>Price: <xsl:value-of select="."/></p>
  24. </xsl:template>
复制代码

xsl:attribute

xsl:attribute用于向输出元素添加属性。

示例:
  1. <xsl:template match="book">
  2.     <div>
  3.         <xsl:attribute name="id">
  4.             <xsl:value-of select="@id"/>
  5.         </xsl:attribute>
  6.         <h2><xsl:value-of select="title"/></h2>
  7.         <p>Author: <xsl:value-of select="author"/></p>
  8.     </div>
  9. </xsl:template>
复制代码

xsl:copy 和 xsl:copy-of

xsl:copy用于复制当前节点(不包括子节点和属性),而xsl:copy-of用于复制当前节点及其所有子节点和属性。

示例:
  1. <xsl:template match="book">
  2.     <xsl:copy>
  3.         <xsl:copy-of select="@*"/>
  4.         <title><xsl:value-of select="title"/></title>
  5.         <author><xsl:value-of select="author"/></author>
  6.     </xsl:copy>
  7. </xsl:template>
复制代码

XSLT高级功能

条件处理

除了前面介绍的xsl:if和xsl:choose,XSLT还提供了其他条件处理方式,如使用XPath函数进行条件判断。

示例:
  1. <xsl:template match="book">
  2.     <div>
  3.         <h2><xsl:value-of select="title"/></h2>
  4.         <p>Genre:
  5.             <xsl:value-of select="concat(genre,
  6.                 if (genre = 'Fantasy') then ' (Fiction)'
  7.                 else if (genre = 'Biography') then ' (Non-Fiction)'
  8.                 else '')"/>
  9.         </p>
  10.     </div>
  11. </xsl:template>
复制代码

循环处理

除了xsl:for-each,XSLT还提供了递归模板调用的方式来实现循环处理,这在处理复杂结构或需要特定迭代逻辑时特别有用。

示例:
  1. <xsl:template name="generate-list">
  2.     <xsl:param name="items"/>
  3.     <xsl:param name="index" select="1"/>
  4.    
  5.     <xsl:if test="$index &lt;= count($items)">
  6.         <li>
  7.             <xsl:value-of select="$items[$index]"/>
  8.         </li>
  9.         <xsl:call-template name="generate-list">
  10.             <xsl:with-param name="items" select="$items"/>
  11.             <xsl:with-param name="index" select="$index + 1"/>
  12.         </xsl:call-template>
  13.     </xsl:if>
  14. </xsl:template>
复制代码

变量和参数的高级用法

XSLT中的变量和参数可以存储各种类型的值,包括节点集、字符串、数字和布尔值。它们还可以用于构建复杂的表达式和逻辑。

示例:
  1. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2.     <xsl:variable name="books-by-genre" select="catalog/book[genre = 'Fantasy']"/>
  3.    
  4.     <xsl:template match="/">
  5.         <html>
  6.             <body>
  7.                 <h1>Fantasy Books</h1>
  8.                 <xsl:call-template name="display-books">
  9.                     <xsl:with-param name="books" select="$books-by-genre"/>
  10.                     <xsl:with-param name="show-price" select="true()"/>
  11.                 </xsl:call-template>
  12.             </body>
  13.         </html>
  14.     </xsl:template>
  15.    
  16.     <xsl:template name="display-books">
  17.         <xsl:param name="books"/>
  18.         <xsl:param name="show-price" select="false()"/>
  19.         
  20.         <xsl:for-each select="$books">
  21.             <div>
  22.                 <h2><xsl:value-of select="title"/></h2>
  23.                 <p>Author: <xsl:value-of select="author"/></p>
  24.                 <xsl:if test="$show-price">
  25.                     <p>Price: <xsl:value-of select="price"/></p>
  26.                 </xsl:if>
  27.             </div>
  28.         </xsl:for-each>
  29.     </xsl:template>
  30. </xsl:stylesheet>
复制代码

模式和模式匹配

XSLT允许为同一个元素定义多个模板,通过模式(mode)来区分它们。这在需要以不同方式处理同一元素时非常有用。

示例:
  1. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2.     <xsl:template match="/">
  3.         <html>
  4.             <body>
  5.                 <h1>Book List - Summary</h1>
  6.                 <xsl:apply-templates select="catalog/book" mode="summary"/>
  7.                
  8.                 <h1>Book List - Details</h1>
  9.                 <xsl:apply-templates select="catalog/book" mode="detail"/>
  10.             </body>
  11.         </html>
  12.     </xsl:template>
  13.    
  14.     <xsl:template match="book" mode="summary">
  15.         <p><xsl:value-of select="title"/> by <xsl:value-of select="author"/></p>
  16.     </xsl:template>
  17.    
  18.     <xsl:template match="book" mode="detail">
  19.         <div>
  20.             <h2><xsl:value-of select="title"/></h2>
  21.             <p>Author: <xsl:value-of select="author"/></p>
  22.             <p>Genre: <xsl:value-of select="genre"/></p>
  23.             <p>Price: <xsl:value-of select="price"/></p>
  24.             <p>Description: <xsl:value-of select="description"/></p>
  25.         </div>
  26.     </xsl:template>
  27. </xsl:stylesheet>
复制代码

键和索引

XSLT提供了xsl:key元素来定义键,用于高效地查找和引用节点。这在处理大型XML文档或需要频繁引用特定节点时特别有用。

示例:
  1. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2.     <xsl:key name="book-by-id" match="book" use="@id"/>
  3.    
  4.     <xsl:template match="/">
  5.         <html>
  6.             <body>
  7.                 <h1>Book References</h1>
  8.                 <xsl:for-each select="catalog/reference">
  9.                     <xsl:variable name="book-id" select="@book-id"/>
  10.                     <p>
  11.                         Reference: <xsl:value-of select="text()"/>
  12.                         <br/>
  13.                         Book: <xsl:value-of select="key('book-by-id', $book-id)/title"/>
  14.                     </p>
  15.                 </xsl:for-each>
  16.             </body>
  17.         </html>
  18.     </xsl:template>
  19. </xsl:stylesheet>
复制代码

数字和日期处理

XSLT提供了丰富的函数来处理数字和日期,包括格式化、计算和转换等操作。

示例:
  1. <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2.     <xsl:template match="/">
  3.         <html>
  4.             <body>
  5.                 <h1>Book Statistics</h1>
  6.                 <p>Total books: <xsl:value-of select="count(catalog/book)"/></p>
  7.                 <p>Average price: <xsl:value-of select="format-number(avg(catalog/book/price), '$#.00')"/></p>
  8.                 <p>Most expensive book: <xsl:value-of select="max(catalog/book/price)"/></p>
  9.                 <p>Current date: <xsl:value-of select="format-date(current-date(), '[D01] [MNn] [Y0001]')"/></p>
  10.             </body>
  11.         </html>
  12.     </xsl:template>
  13. </xsl:stylesheet>
复制代码

字符串处理

XSLT提供了多种字符串处理函数,如连接、分割、替换和格式化等。

示例:
  1. <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2.     <xsl:template match="/">
  3.         <html>
  4.             <body>
  5.                 <h1>Book Titles</h1>
  6.                 <xsl:for-each select="catalog/book">
  7.                     <p>
  8.                         Original: <xsl:value-of select="title"/>
  9.                         <br/>
  10.                         Upper case: <xsl:value-of select="upper-case(title)"/>
  11.                         <br/>
  12.                         Length: <xsl:value-of select="string-length(title)"/>
  13.                         <br/>
  14.                         First 10 characters: <xsl:value-of select="substring(title, 1, 10)"/>
  15.                     </p>
  16.                 </xsl:for-each>
  17.             </body>
  18.         </html>
  19.     </xsl:template>
  20. </xsl:stylesheet>
复制代码

实际应用案例

案例1:XML到HTML的转换

假设我们有一个包含书籍信息的XML文档,我们想要将其转换为HTML格式以便在网页上显示。

源XML文档(books.xml):
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <catalog>
  3.     <book id="bk101">
  4.         <title>XML Developer's Guide</title>
  5.         <author>Gambardella, Matthew</author>
  6.         <genre>Computer</genre>
  7.         <price>44.95</price>
  8.         <publish_date>2000-10-01</publish_date>
  9.         <description>An in-depth look at creating applications with XML.</description>
  10.     </book>
  11.     <book id="bk102">
  12.         <title>Midnight Rain</title>
  13.         <author>Ralls, Kim</author>
  14.         <genre>Fantasy</genre>
  15.         <price>5.95</price>
  16.         <publish_date>2000-12-16</publish_date>
  17.         <description>A former architect battles corporate zombies.</description>
  18.     </book>
  19.     <book id="bk103">
  20.         <title>Maeve Ascendant</title>
  21.         <author>Corets, Eva</author>
  22.         <genre>Fantasy</genre>
  23.         <price>5.95</price>
  24.         <publish_date>2000-11-17</publish_date>
  25.         <description>After the collapse of a nanotechnology society, the young survivors band together.</description>
  26.     </book>
  27. </catalog>
复制代码

XSLT样式表(books-to-html.xsl):
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  3.     <xsl:output method="html" indent="yes" encoding="UTF-8"/>
  4.    
  5.     <xsl:template match="/">
  6.         <html>
  7.             <head>
  8.                 <title>Book Catalog</title>
  9.                 <style>
  10.                     body { font-family: Arial, sans-serif; }
  11.                     .book { margin-bottom: 20px; padding: 10px; border: 1px solid #ccc; }
  12.                     .title { font-weight: bold; font-size: 1.2em; color: #0066cc; }
  13.                     .author { font-style: italic; }
  14.                     .price { color: #009900; font-weight: bold; }
  15.                     .genre { background-color: #f0f0f0; padding: 2px 5px; border-radius: 3px; }
  16.                 </style>
  17.             </head>
  18.             <body>
  19.                 <h1>Book Catalog</h1>
  20.                 <xsl:apply-templates select="catalog/book"/>
  21.             </body>
  22.         </html>
  23.     </xsl:template>
  24.    
  25.     <xsl:template match="book">
  26.         <div class="book">
  27.             <div class="title"><xsl:value-of select="title"/></div>
  28.             <div class="author">by <xsl:value-of select="author"/></div>
  29.             <div>Genre: <span class="genre"><xsl:value-of select="genre"/></span></div>
  30.             <div class="price">Price: $<xsl:value-of select="price"/></div>
  31.             <div>Published: <xsl:value-of select="publish_date"/></div>
  32.             <div><xsl:value-of select="description"/></div>
  33.         </div>
  34.     </xsl:template>
  35. </xsl:stylesheet>
复制代码

转换后的HTML输出:
  1. <html>
  2.     <head>
  3.         <title>Book Catalog</title>
  4.         <style>
  5.             body { font-family: Arial, sans-serif; }
  6.             .book { margin-bottom: 20px; padding: 10px; border: 1px solid #ccc; }
  7.             .title { font-weight: bold; font-size: 1.2em; color: #0066cc; }
  8.             .author { font-style: italic; }
  9.             .price { color: #009900; font-weight: bold; }
  10.             .genre { background-color: #f0f0f0; padding: 2px 5px; border-radius: 3px; }
  11.         </style>
  12.     </head>
  13.     <body>
  14.         <h1>Book Catalog</h1>
  15.         <div class="book">
  16.             <div class="title">XML Developer's Guide</div>
  17.             <div class="author">by Gambardella, Matthew</div>
  18.             <div>Genre: <span class="genre">Computer</span></div>
  19.             <div class="price">Price: $44.95</div>
  20.             <div>Published: 2000-10-01</div>
  21.             <div>An in-depth look at creating applications with XML.</div>
  22.         </div>
  23.         <div class="book">
  24.             <div class="title">Midnight Rain</div>
  25.             <div class="author">by Ralls, Kim</div>
  26.             <div>Genre: <span class="genre">Fantasy</span></div>
  27.             <div class="price">Price: $5.95</div>
  28.             <div>Published: 2000-12-16</div>
  29.             <div>A former architect battles corporate zombies.</div>
  30.         </div>
  31.         <div class="book">
  32.             <div class="title">Maeve Ascendant</div>
  33.             <div class="author">by Corets, Eva</div>
  34.             <div>Genre: <span class="genre">Fantasy</span></div>
  35.             <div class="price">Price: $5.95</div>
  36.             <div>Published: 2000-11-17</div>
  37.             <div>After the collapse of a nanotechnology society, the young survivors band together.</div>
  38.         </div>
  39.     </body>
  40. </html>
复制代码

案例2:XML到XML的转换

在这个例子中,我们将把一个XML文档转换为另一个具有不同结构的XML文档。假设我们有一个包含订单信息的XML文档,我们想要将其转换为发票格式的XML文档。

源XML文档(order.xml):
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <order id="ORD12345">
  3.     <customer>
  4.         <name>John Doe</name>
  5.         <address>123 Main St, Anytown, USA</address>
  6.         <email>john.doe@example.com</email>
  7.     </customer>
  8.     <items>
  9.         <item id="IT001">
  10.             <name>Laptop</name>
  11.             <quantity>1</quantity>
  12.             <price>999.99</price>
  13.         </item>
  14.         <item id="IT002">
  15.             <name>Mouse</name>
  16.             <quantity>2</quantity>
  17.             <price>19.99</price>
  18.         </item>
  19.         <item id="IT003">
  20.             <name>Keyboard</name>
  21.             <quantity>1</quantity>
  22.             <price>49.99</price>
  23.         </item>
  24.     </items>
  25.     <order_date>2023-05-15</order_date>
  26.     <shipping_method>Express</shipping_method>
  27. </order>
复制代码

XSLT样式表(order-to-invoice.xsl):
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  3.     <xsl:output method="xml" indent="yes" encoding="UTF-8"/>
  4.    
  5.     <xsl:template match="/">
  6.         <invoice>
  7.             <xsl:attribute name="invoice_id">
  8.                 <xsl:value-of select="concat('INV', substring-after(order/@id, 'ORD'))"/>
  9.             </xsl:attribute>
  10.             <xsl:attribute name="order_id">
  11.                 <xsl:value-of select="order/@id"/>
  12.             </xsl:attribute>
  13.             <xsl:attribute name="invoice_date">
  14.                 <xsl:value-of select="current-date()"/>
  15.             </xsl:attribute>
  16.             
  17.             <bill_to>
  18.                 <name><xsl:value-of select="order/customer/name"/></name>
  19.                 <address><xsl:value-of select="order/customer/address"/></address>
  20.                 <email><xsl:value-of select="order/customer/email"/></email>
  21.             </bill_to>
  22.             
  23.             <invoice_items>
  24.                 <xsl:apply-templates select="order/items/item"/>
  25.             </invoice_items>
  26.             
  27.             <summary>
  28.                 <subtotal><xsl:value-of select="sum(order/items/item/(price * quantity))"/></subtotal>
  29.                 <tax><xsl:value-of select="sum(order/items/item/(price * quantity)) * 0.08"/></tax>
  30.                 <shipping>
  31.                     <xsl:choose>
  32.                         <xsl:when test="order/shipping_method = 'Express'">25.00</xsl:when>
  33.                         <xsl:otherwise>10.00</xsl:otherwise>
  34.                     </xsl:choose>
  35.                 </shipping>
  36.                 <total>
  37.                     <xsl:value-of select="sum(order/items/item/(price * quantity)) * 1.08 +
  38.                         (order/shipping_method = 'Express' * 25 + (order/shipping_method != 'Express') * 10)"/>
  39.                 </total>
  40.             </summary>
  41.         </invoice>
  42.     </xsl:template>
  43.    
  44.     <xsl:template match="item">
  45.         <item>
  46.             <xsl:attribute name="id">
  47.                 <xsl:value-of select="@id"/>
  48.             </xsl:attribute>
  49.             <name><xsl:value-of select="name"/></name>
  50.             <quantity><xsl:value-of select="quantity"/></quantity>
  51.             <unit_price><xsl:value-of select="price"/></unit_price>
  52.             <total_price><xsl:value-of select="price * quantity"/></total_price>
  53.         </item>
  54.     </xsl:template>
  55. </xsl:stylesheet>
复制代码

转换后的XML输出(invoice.xml):
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <invoice invoice_id="INV12345" order_id="ORD12345" invoice_date="2023-05-20">
  3.     <bill_to>
  4.         <name>John Doe</name>
  5.         <address>123 Main St, Anytown, USA</address>
  6.         <email>john.doe@example.com</email>
  7.     </bill_to>
  8.     <invoice_items>
  9.         <item id="IT001">
  10.             <name>Laptop</name>
  11.             <quantity>1</quantity>
  12.             <unit_price>999.99</unit_price>
  13.             <total_price>999.99</total_price>
  14.         </item>
  15.         <item id="IT002">
  16.             <name>Mouse</name>
  17.             <quantity>2</quantity>
  18.             <unit_price>19.99</unit_price>
  19.             <total_price>39.98</total_price>
  20.         </item>
  21.         <item id="IT003">
  22.             <name>Keyboard</name>
  23.             <quantity>1</quantity>
  24.             <unit_price>49.99</unit_price>
  25.             <total_price>49.99</total_price>
  26.         </item>
  27.     </invoice_items>
  28.     <summary>
  29.         <subtotal>1089.96</subtotal>
  30.         <tax>87.1968</tax>
  31.         <shipping>25.00</shipping>
  32.         <total>1202.1568</total>
  33.     </summary>
  34. </invoice>
复制代码

案例3:XML到CSV的转换

在这个例子中,我们将把一个包含员工信息的XML文档转换为CSV格式,以便在电子表格软件中处理。

源XML文档(employees.xml):
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <employees>
  3.     <employee id="EMP001">
  4.         <name>John Smith</name>
  5.         <department>IT</department>
  6.         <position>Developer</position>
  7.         <salary>75000</salary>
  8.         <hire_date>2018-05-15</hire_date>
  9.     </employee>
  10.     <employee id="EMP002">
  11.         <name>Jane Doe</name>
  12.         <department>HR</department>
  13.         <position>Manager</position>
  14.         <salary>85000</salary>
  15.         <hire_date>2016-08-22</hire_date>
  16.     </employee>
  17.     <employee id="EMP003">
  18.         <name>Bob Johnson</name>
  19.         <department>Finance</department>
  20.         <position>Analyst</position>
  21.         <salary>65000</salary>
  22.         <hire_date>2020-01-10</hire_date>
  23.     </employee>
  24. </employees>
复制代码

XSLT样式表(employees-to-csv.xsl):
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  3.     <xsl:output method="text" encoding="UTF-8"/>
  4.    
  5.     <xsl:template match="/">
  6.         <xsl:text>ID,Name,Department,Position,Salary,Hire Date&#10;</xsl:text>
  7.         <xsl:apply-templates select="employees/employee"/>
  8.     </xsl:template>
  9.    
  10.     <xsl:template match="employee">
  11.         <xsl:value-of select="@id"/>
  12.         <xsl:text>,</xsl:text>
  13.         <xsl:value-of select="name"/>
  14.         <xsl:text>,</xsl:text>
  15.         <xsl:value-of select="department"/>
  16.         <xsl:text>,</xsl:text>
  17.         <xsl:value-of select="position"/>
  18.         <xsl:text>,</xsl:text>
  19.         <xsl:value-of select="salary"/>
  20.         <xsl:text>,</xsl:text>
  21.         <xsl:value-of select="hire_date"/>
  22.         <xsl:text>&#10;</xsl:text>
  23.     </xsl:template>
  24. </xsl:stylesheet>
复制代码

转换后的CSV输出(employees.csv):
  1. ID,Name,Department,Position,Salary,Hire Date
  2. EMP001,John Smith,IT,Developer,75000,2018-05-15
  3. EMP002,Jane Doe,HR,Manager,85000,2016-08-22
  4. EMP003,Bob Johnson,Finance,Analyst,65000,2020-01-10
复制代码

案例4:复杂XML结构的处理

在这个例子中,我们将处理一个更复杂的XML结构,包含嵌套元素和多个命名空间。假设我们有一个包含产品目录的XML文档,我们想要生成一个按类别分组的HTML页面。

源XML文档(products.xml):
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <catalog xmlns="http://example.com/catalog" xmlns:media="http://example.com/media">
  3.     <category id="CAT001" name="Electronics">
  4.         <product id="PRD001">
  5.             <name>Smartphone</name>
  6.             <description>A high-end smartphone with advanced features</description>
  7.             <price currency="USD">699.99</price>
  8.             <specifications>
  9.                 <spec name="Screen Size">6.5 inches</spec>
  10.                 <spec name="Storage">128 GB</spec>
  11.                 <spec name="RAM">6 GB</spec>
  12.             </specifications>
  13.             <media:images>
  14.                 <media:image url="images/smartphone_front.jpg" type="front"/>
  15.                 <media:image url="images/smartphone_back.jpg" type="back"/>
  16.             </media:images>
  17.         </product>
  18.         <product id="PRD002">
  19.             <name>Laptop</name>
  20.             <description>Powerful laptop for work and gaming</description>
  21.             <price currency="USD">1299.99</price>
  22.             <specifications>
  23.                 <spec name="Screen Size">15.6 inches</spec>
  24.                 <spec name="Storage">512 GB SSD</spec>
  25.                 <spec name="RAM">16 GB</spec>
  26.             </specifications>
  27.             <media:images>
  28.                 <media:image url="images/laptop_open.jpg" type="open"/>
  29.                 <media:image url="images/laptop_closed.jpg" type="closed"/>
  30.             </media:images>
  31.         </product>
  32.     </category>
  33.     <category id="CAT002" name="Home Appliances">
  34.         <product id="PRD003">
  35.             <name>Refrigerator</name>
  36.             <description>Energy-efficient refrigerator with ice maker</description>
  37.             <price currency="USD">899.99</price>
  38.             <specifications>
  39.                 <spec name="Capacity">25 cubic feet</spec>
  40.                 <spec name="Energy Rating">A++</spec>
  41.                 <spec name="Features">Ice maker, Water dispenser</spec>
  42.             </specifications>
  43.             <media:images>
  44.                 <media:image url="images/refrigerator_exterior.jpg" type="exterior"/>
  45.                 <media:image url="images/refrigerator_interior.jpg" type="interior"/>
  46.             </media:images>
  47.         </product>
  48.     </category>
  49. </catalog>
复制代码

XSLT样式表(products-to-html.xsl):
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <xsl:stylesheet version="1.0"
  3.     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  4.     xmlns:cat="http://example.com/catalog"
  5.     xmlns:media="http://example.com/media"
  6.     exclude-result-prefixes="cat media">
  7.    
  8.     <xsl:output method="html" indent="yes" encoding="UTF-8"/>
  9.    
  10.     <xsl:template match="/">
  11.         <html>
  12.             <head>
  13.                 <title>Product Catalog</title>
  14.                 <style>
  15.                     body { font-family: Arial, sans-serif; margin: 20px; }
  16.                     .category { margin-bottom: 30px; }
  17.                     .category-header { background-color: #f0f0f0; padding: 10px; font-size: 1.2em; font-weight: bold; }
  18.                     .product { margin: 15px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
  19.                     .product-name { font-weight: bold; font-size: 1.1em; color: #333; }
  20.                     .product-price { color: #009900; font-weight: bold; }
  21.                     .specifications { margin: 10px 0; }
  22.                     .spec { margin: 5px 0; }
  23.                     .images { margin: 10px 0; }
  24.                     .image { display: inline-block; margin-right: 10px; }
  25.                 </style>
  26.             </head>
  27.             <body>
  28.                 <h1>Product Catalog</h1>
  29.                 <xsl:apply-templates select="cat:catalog/cat:category"/>
  30.             </body>
  31.         </html>
  32.     </xsl:template>
  33.    
  34.     <xsl:template match="cat:category">
  35.         <div class="category">
  36.             <div class="category-header">
  37.                 <xsl:value-of select="@name"/>
  38.             </div>
  39.             <xsl:apply-templates select="cat:product"/>
  40.         </div>
  41.     </xsl:template>
  42.    
  43.     <xsl:template match="cat:product">
  44.         <div class="product">
  45.             <div class="product-name">
  46.                 <xsl:value-of select="cat:name"/>
  47.             </div>
  48.             <div>
  49.                 <xsl:value-of select="cat:description"/>
  50.             </div>
  51.             <div class="product-price">
  52.                 Price: <xsl:value-of select="cat:price"/> <xsl:value-of select="cat:price/@currency"/>
  53.             </div>
  54.             <div class="specifications">
  55.                 <h3>Specifications:</h3>
  56.                 <xsl:for-each select="cat:specifications/cat:spec">
  57.                     <div class="spec">
  58.                         <strong><xsl:value-of select="@name"/>:</strong> <xsl:value-of select="."/>
  59.                     </div>
  60.                 </xsl:for-each>
  61.             </div>
  62.             <div class="images">
  63.                 <h3>Images:</h3>
  64.                 <xsl:for-each select="media:images/media:image">
  65.                     <div class="image">
  66.                         <img src="{@url}" alt="{@type} view" width="150"/>
  67.                         <div><xsl:value-of select="@type"/></div>
  68.                     </div>
  69.                 </xsl:for-each>
  70.             </div>
  71.         </div>
  72.     </xsl:template>
  73. </xsl:stylesheet>
复制代码

转换后的HTML输出:
  1. <html>
  2.     <head>
  3.         <title>Product Catalog</title>
  4.         <style>
  5.             body { font-family: Arial, sans-serif; margin: 20px; }
  6.             .category { margin-bottom: 30px; }
  7.             .category-header { background-color: #f0f0f0; padding: 10px; font-size: 1.2em; font-weight: bold; }
  8.             .product { margin: 15px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
  9.             .product-name { font-weight: bold; font-size: 1.1em; color: #333; }
  10.             .product-price { color: #009900; font-weight: bold; }
  11.             .specifications { margin: 10px 0; }
  12.             .spec { margin: 5px 0; }
  13.             .images { margin: 10px 0; }
  14.             .image { display: inline-block; margin-right: 10px; }
  15.         </style>
  16.     </head>
  17.     <body>
  18.         <h1>Product Catalog</h1>
  19.         <div class="category">
  20.             <div class="category-header">Electronics</div>
  21.             <div class="product">
  22.                 <div class="product-name">Smartphone</div>
  23.                 <div>A high-end smartphone with advanced features</div>
  24.                 <div class="product-price">Price: 699.99 USD</div>
  25.                 <div class="specifications">
  26.                     <h3>Specifications:</h3>
  27.                     <div class="spec"><strong>Screen Size:</strong> 6.5 inches</div>
  28.                     <div class="spec"><strong>Storage:</strong> 128 GB</div>
  29.                     <div class="spec"><strong>RAM:</strong> 6 GB</div>
  30.                 </div>
  31.                 <div class="images">
  32.                     <h3>Images:</h3>
  33.                     <div class="image">
  34.                         <img src="images/smartphone_front.jpg" alt="front view" width="150">
  35.                         <div>front</div>
  36.                     </div>
  37.                     <div class="image">
  38.                         <img src="images/smartphone_back.jpg" alt="back view" width="150">
  39.                         <div>back</div>
  40.                     </div>
  41.                 </div>
  42.             </div>
  43.             <div class="product">
  44.                 <div class="product-name">Laptop</div>
  45.                 <div>Powerful laptop for work and gaming</div>
  46.                 <div class="product-price">Price: 1299.99 USD</div>
  47.                 <div class="specifications">
  48.                     <h3>Specifications:</h3>
  49.                     <div class="spec"><strong>Screen Size:</strong> 15.6 inches</div>
  50.                     <div class="spec"><strong>Storage:</strong> 512 GB SSD</div>
  51.                     <div class="spec"><strong>RAM:</strong> 16 GB</div>
  52.                 </div>
  53.                 <div class="images">
  54.                     <h3>Images:</h3>
  55.                     <div class="image">
  56.                         <img src="images/laptop_open.jpg" alt="open view" width="150">
  57.                         <div>open</div>
  58.                     </div>
  59.                     <div class="image">
  60.                         <img src="images/laptop_closed.jpg" alt="closed view" width="150">
  61.                         <div>closed</div>
  62.                     </div>
  63.                 </div>
  64.             </div>
  65.         </div>
  66.         <div class="category">
  67.             <div class="category-header">Home Appliances</div>
  68.             <div class="product">
  69.                 <div class="product-name">Refrigerator</div>
  70.                 <div>Energy-efficient refrigerator with ice maker</div>
  71.                 <div class="product-price">Price: 899.99 USD</div>
  72.                 <div class="specifications">
  73.                     <h3>Specifications:</h3>
  74.                     <div class="spec"><strong>Capacity:</strong> 25 cubic feet</div>
  75.                     <div class="spec"><strong>Energy Rating:</strong> A++</div>
  76.                     <div class="spec"><strong>Features:</strong> Ice maker, Water dispenser</div>
  77.                 </div>
  78.                 <div class="images">
  79.                     <h3>Images:</h3>
  80.                     <div class="image">
  81.                         <img src="images/refrigerator_exterior.jpg" alt="exterior view" width="150">
  82.                         <div>exterior</div>
  83.                     </div>
  84.                     <div class="image">
  85.                         <img src="images/refrigerator_interior.jpg" alt="interior view" width="150">
  86.                         <div>interior</div>
  87.                     </div>
  88.                 </div>
  89.             </div>
  90.         </div>
  91.     </body>
  92. </html>
复制代码

XSLT最佳实践和性能优化

模板设计原则

1. 保持模板简单和专注:每个模板应该专注于处理一种特定类型的节点,避免过于复杂的逻辑。
2. 使用模板匹配而不是条件语句:尽可能使用模板匹配(xsl:template的match属性)而不是条件语句(xsl:if或xsl:choose),这样可以更好地利用XSLT的处理模型。
3. 避免过度使用xsl:for-each:虽然xsl:for-each在某些情况下很有用,但过度使用会导致代码难以维护。考虑使用模板匹配和xsl:apply-templates代替。

保持模板简单和专注:每个模板应该专注于处理一种特定类型的节点,避免过于复杂的逻辑。

使用模板匹配而不是条件语句:尽可能使用模板匹配(xsl:template的match属性)而不是条件语句(xsl:if或xsl:choose),这样可以更好地利用XSLT的处理模型。

避免过度使用xsl:for-each:虽然xsl:for-each在某些情况下很有用,但过度使用会导致代码难以维护。考虑使用模板匹配和xsl:apply-templates代替。

性能优化技巧

1. 使用键(key)提高查找效率:对于频繁的节点查找,使用xsl:key定义键可以显著提高性能。

示例:
  1. <xsl:key name="product-by-id" match="product" use="@id"/>
  2. <!-- 使用键查找产品 -->
  3. <xsl:value-of select="key('product-by-id', 'PRD001')/name"/>
复制代码

1. 避免在循环中使用XPath表达式:在xsl:for-each循环中,避免在每次迭代中重复计算相同的XPath表达式。考虑使用变量存储结果。

示例:
  1. <!-- 不推荐 -->
  2. <xsl:for-each select="products/product">
  3.     <xsl:if test="price &gt; catalog/min_price">
  4.         <!-- 处理产品 -->
  5.     </xsl:if>
  6. </xsl:for-each>
  7. <!-- 推荐 -->
  8. <xsl:variable name="min-price" select="catalog/min_price"/>
  9. <xsl:for-each select="products/product">
  10.     <xsl:if test="price &gt; $min-price">
  11.         <!-- 处理产品 -->
  12.     </xsl:if>
  13. </xsl:for-each>
复制代码

1. 使用适当的XPath表达式:避免使用过于宽泛的XPath表达式,如//,它们会导致处理器搜索整个文档。

示例:
  1. <!-- 不推荐 -->
  2. <xsl:value-of select="//product[@id='PRD001']/name"/>
  3. <!-- 推荐 -->
  4. <xsl:value-of select="catalog/category/product[@id='PRD001']/name"/>
复制代码

1. 减少输出的大小:如果输出文档很大,考虑使用xsl:output的indent="no"属性来减少空白字符。
2. 使用XSLT 2.0或更高版本:如果可能,使用XSLT 2.0或3.0,它们提供了更多的功能和更好的性能。

减少输出的大小:如果输出文档很大,考虑使用xsl:output的indent="no"属性来减少空白字符。

使用XSLT 2.0或更高版本:如果可能,使用XSLT 2.0或3.0,它们提供了更多的功能和更好的性能。

可维护性建议

1. 使用注释和文档:为复杂的XSLT代码添加注释,解释其目的和工作方式。
2. 模块化样式表:使用xsl:import和xsl:include将大型XSLT样式表分解为更小、更易管理的模块。

使用注释和文档:为复杂的XSLT代码添加注释,解释其目的和工作方式。

模块化样式表:使用xsl:import和xsl:include将大型XSLT样式表分解为更小、更易管理的模块。

示例:
  1. <!-- 主样式表 -->
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  3.     <xsl:import href="common-templates.xsl"/>
  4.     <xsl:import href="product-templates.xsl"/>
  5.     <xsl:import href="formatting-templates.xsl"/>
  6.    
  7.     <!-- 主样式表内容 -->
  8. </xsl:stylesheet>
复制代码

1. 使用命名约定:为变量、参数和模板使用一致的命名约定,以提高代码的可读性。
2. 避免硬编码值:将可能变化的值(如文本标签、格式选项等)提取为变量或参数,以便于修改。

使用命名约定:为变量、参数和模板使用一致的命名约定,以提高代码的可读性。

避免硬编码值:将可能变化的值(如文本标签、格式选项等)提取为变量或参数,以便于修改。

调试和测试

1. 使用XSLT调试器:许多XSLT处理器和IDE提供了调试工具,可以帮助你逐步执行XSLT代码并检查变量值。
2. 输出中间结果:在开发过程中,使用xsl:message或临时输出元素来检查中间结果。

使用XSLT调试器:许多XSLT处理器和IDE提供了调试工具,可以帮助你逐步执行XSLT代码并检查变量值。

输出中间结果:在开发过程中,使用xsl:message或临时输出元素来检查中间结果。

示例:
  1. <xsl:template match="product">
  2.     <xsl:message>Processing product: <xsl:value-of select="@id"/></xsl:message>
  3.     <!-- 模板内容 -->
  4. </xsl:template>
复制代码

1. 测试各种输入场景:确保你的XSLT代码能够处理各种输入情况,包括边界情况和错误情况。
2. 使用XSLT测试框架:考虑使用XSLT测试框架(如XSpec)来自动化测试过程。

测试各种输入场景:确保你的XSLT代码能够处理各种输入情况,包括边界情况和错误情况。

使用XSLT测试框架:考虑使用XSLT测试框架(如XSpec)来自动化测试过程。

常见问题和解决方案

问题1:处理命名空间

问题:当源XML文档使用命名空间时,XPath表达式可能无法正确匹配节点。

解决方案:在XSLT样式表中声明相同的命名空间,并在XPath表达式中使用前缀。

示例:
  1. <!-- 源XML -->
  2. <catalog xmlns="http://example.com/catalog">
  3.     <product id="PRD001">
  4.         <name>Smartphone</name>
  5.     </product>
  6. </catalog>
  7. <!-- XSLT样式表 -->
  8. <xsl:stylesheet version="1.0"
  9.     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  10.     xmlns:cat="http://example.com/catalog"
  11.     exclude-result-prefixes="cat">
  12.    
  13.     <xsl:template match="/">
  14.         <xsl:value-of select="cat:catalog/cat:product/cat:name"/>
  15.     </xsl:template>
  16. </xsl:stylesheet>
复制代码

问题2:处理特殊字符和CDATA

问题:源XML中的特殊字符(如<, >, &)或CDATA部分可能无法正确处理或输出。

解决方案:使用xsl:text或xsl:output的相应属性来控制特殊字符的处理。

示例:
  1. <!-- 输出包含特殊字符的文本 -->
  2. <xsl:text>This is a &lt;test&gt; with special characters.</xsl:text>
  3. <!-- 输出CDATA部分 -->
  4. <xsl:text disable-output-escaping="yes">&lt;![CDATA[This is CDATA content]]&gt;</xsl:text>
复制代码

问题3:处理日期和时间

问题:XSLT 1.0对日期和时间的处理能力有限,难以进行日期计算和格式化。

解决方案:在XSLT 1.0中使用扩展函数或字符串操作,或者升级到XSLT 2.0/3.0,它们提供了丰富的日期和时间函数。

示例(XSLT 2.0):
  1. <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2.     <xsl:template match="/">
  3.         <xsl:variable name="today" select="current-date()"/>
  4.         <xsl:variable name="order-date" select="xs:date('2023-05-15')"/>
  5.         
  6.         <p>Today: <xsl:value-of select="format-date($today, '[D01] [MNn] [Y0001]')"/></p>
  7.         <p>Order date: <xsl:value-of select="format-date($order-date, '[D01] [MNn] [Y0001]')"/></p>
  8.         <p>Days since order: <xsl:value-of select="days-from-duration($today - $order-date)"/></p>
  9.     </xsl:template>
  10. </xsl:stylesheet>
复制代码

问题4:处理大型XML文档

问题:当处理大型XML文档时,可能会遇到内存不足或性能问题。

解决方案:

1. 使用流式处理(XSLT 3.0的流式转换)
2. 优化XPath表达式,避免使用//
3. 使用键(key)提高查找效率
4. 考虑将大型文档分解为较小的部分进行处理

示例(XSLT 3.0流式处理):
  1. <xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2.     <xsl:mode streamable="yes"/>
  3.    
  4.     <xsl:template match="/">
  5.         <html>
  6.             <body>
  7.                 <h1>Large Document Processing</h1>
  8.                 <xsl:apply-templates select="large-document/record"/>
  9.             </body>
  10.         </html>
  11.     </xsl:template>
  12.    
  13.     <xsl:template match="record">
  14.         <div>
  15.             <xsl:value-of select="id"/>: <xsl:value-of select="name"/>
  16.         </div>
  17.     </xsl:template>
  18. </xsl:stylesheet>
复制代码

问题5:处理多语言和国际化

问题:需要根据不同的语言环境生成不同语言的输出,或者处理多语言内容。

解决方案:使用参数和变量来控制语言选择,或者使用专门的国际化技术。

示例:
  1. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2.     <xsl:param name="lang" select="'en'"/>
  3.    
  4.     <xsl:variable name="texts">
  5.         <text lang="en" name="title">Product Catalog</text>
  6.         <text lang="en" name="price">Price</text>
  7.         <text lang="fr" name="title">Catalogue de Produits</text>
  8.         <text lang="fr" name="price">Prix</text>
  9.     </xsl:variable>
  10.    
  11.     <xsl:template name="get-text">
  12.         <xsl:param name="name"/>
  13.         <xsl:value-of select="$texts/text[@lang=$lang and @name=$name]"/>
  14.     </xsl:template>
  15.    
  16.     <xsl:template match="/">
  17.         <html>
  18.             <body>
  19.                 <h1><xsl:call-template name="get-text"><xsl:with-param name="name" select="'title'"/></xsl:call-template></h1>
  20.                 <xsl:apply-templates select="catalog/product"/>
  21.             </body>
  22.         </html>
  23.     </xsl:template>
  24.    
  25.     <xsl:template match="product">
  26.         <div>
  27.             <h2><xsl:value-of select="name"/></h2>
  28.             <p>
  29.                 <xsl:call-template name="get-text"><xsl:with-param name="name" select="'price'"/></xsl:call-template>:
  30.                 <xsl:value-of select="price"/>
  31.             </p>
  32.         </div>
  33.     </xsl:template>
  34. </xsl:stylesheet>
复制代码

总结与展望

XSLT是一种强大而灵活的语言,用于转换XML文档。通过本文的介绍,我们了解了XSLT的基础语法、核心元素、高级功能以及实际应用案例。无论是将XML转换为HTML用于网页显示,还是转换为其他XML格式以满足不同系统的需求,XSLT都能提供有效的解决方案。

随着XML在数据交换和文档处理领域的广泛应用,掌握XSLT技能变得越来越重要。通过遵循最佳实践和性能优化技巧,我们可以开发出高效、可维护的XSLT样式表,解决各种复杂的数据转换问题。

展望未来,XSLT仍在不断发展。XSLT 3.0引入了许多新特性,如流式处理、更高阶的函数和更好的JSON支持,使其能够适应现代数据处理的需求。随着这些新特性的普及,XSLT将继续在数据转换和处理领域发挥重要作用。

无论你是初学者还是有经验的开发者,希望本文能够帮助你更好地理解和应用XSLT,轻松实现XML数据的格式化与转换。通过不断学习和实践,你将能够掌握这一强大的技术,为你的项目带来更多的可能性和价值。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

加入Discord频道

加入Discord频道

加入QQ社群

加入QQ社群

联系我们|小黑屋|TG频道|RSS |网站地图

Powered by Pixtech

© 2025-2026 Pixtech Team.