xml – xsl:template match属性中的正则表达式

前端之家收集整理的这篇文章主要介绍了xml – xsl:template match属性中的正则表达式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我只想知道是否可以在xsl:template元素的match属性中使用正则表达式.
例如,假设我有以下 XML文档:
  1. <greeting>
  2. <aaa>Hello</aaa>
  3. <bbb>Good</bbb>
  4. <ccc>Excellent</ccc>
  5. <dddline>Line</dddline>
  6. </greeting>

现在XSLT转换上面的文件

  1. <xsl:stylesheet>
  2.  
  3. <xsl:template match="/">
  4. <xsl:apply-templates select="*"/>
  5. </xsl:template>
  6.  
  7. <xsl:template match="matches(node-name(*),'line')">
  8. <xsl:value-of select="."/>
  9. </xsl:template>
  10.  
  11. </xsl:stylesheet>

当我尝试在xsl:template元素的match属性中使用语法matches(node-name(*),’line $’)时,它会检索错误消息.我可以在match属性中使用正则表达式吗?

非常感谢

这是正确的XSLT 1.0匹配方式(在XSLT 2.0中使用matches()函数和真实的RegEx作为模式参数):

匹配名称中包含“line”的元素:

  1. <xsl:template match="*[contains(name(),'line')]">
  2. <!-- Whatever processing is necessary -->
  3. </xsl:template>

匹配名称以’line’结尾的元素:

  1. <xsl:template match="*[substring(name(),string-length() -3) = 'line']">
  2. <!-- Whatever processing is necessary -->
  3. </xsl:template>

@Tomalak提供了另一种XSLT 1.0方法来查找以给定字符串结尾的名称.他的解决方案使用了一个特殊字符,保证不会以任何名称出现.我的解决方案可用于查找是否有任何字符串(不仅是元素的名称)以另一个给定字符串结尾.

在XSLT 2.x中:

使用:matches(name(),’.* line $’)匹配以字符串“line”结尾的名称

这种转变:



当应用于theis XML文档时:

  1. <greeting>
  2. <aaa>Hello</aaa>
  3. <bblineb>Good</bblineb>
  4. <ccc>Excellent</ccc>
  5. <dddline>Line</dddline>
  6. </greeting>

仅将输出复制到元素的元素,其名称以字符串“line”结尾:

  1. <dddline>Line</dddline>

这个转换(使用匹配(name(),’.* line’)):

  1. <xsl:stylesheet version="2.0"
  2. xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  3. xmlns:xs="http://www.w3.org/2001/XMLSchema">
  4. <xsl:output omit-xml-declaration="yes" indent="yes"/>
  5.  
  6. <xsl:template match="*[matches(name(),'.*line')]">
  7. <xsl:copy-of select="."/>
  8. </xsl:template>
  9.  
  10. <xsl:template match="*[not(matches(name(),'.*line'))]">
  11. <xsl:apply-templates select="node()[not(self::text())]"/>
  12. </xsl:template>
  13. </xsl:stylesheet>

将所有元素复制到输出,其名称包含字符串“line”:

  1. <bblineb>Good</bblineb>
  2. <dddline>Line</dddline>

猜你在找的XML相关文章