我只想知道是否可以在xsl:template元素的match属性中使用正则表达式.
例如,假设我有以下 XML文档:
例如,假设我有以下 XML文档:
- <greeting>
- <aaa>Hello</aaa>
- <bbb>Good</bbb>
- <ccc>Excellent</ccc>
- <dddline>Line</dddline>
- </greeting>
现在XSLT转换上面的文件:
- <xsl:stylesheet>
- <xsl:template match="/">
- <xsl:apply-templates select="*"/>
- </xsl:template>
- <xsl:template match="matches(node-name(*),'line')">
- <xsl:value-of select="."/>
- </xsl:template>
- </xsl:stylesheet>
当我尝试在xsl:template元素的match属性中使用语法matches(node-name(*),’line $’)时,它会检索错误消息.我可以在match属性中使用正则表达式吗?
非常感谢
这是正确的XSLT 1.0匹配方式(在XSLT 2.0中使用matches()函数和真实的RegEx作为模式参数):
匹配名称中包含“line”的元素:
- <xsl:template match="*[contains(name(),'line')]">
- <!-- Whatever processing is necessary -->
- </xsl:template>
匹配名称以’line’结尾的元素:
- <xsl:template match="*[substring(name(),string-length() -3) = 'line']">
- <!-- Whatever processing is necessary -->
- </xsl:template>
@Tomalak提供了另一种XSLT 1.0方法来查找以给定字符串结尾的名称.他的解决方案使用了一个特殊字符,保证不会以任何名称出现.我的解决方案可用于查找是否有任何字符串(不仅是元素的名称)以另一个给定字符串结尾.
在XSLT 2.x中:
使用:matches(name(),’.* line $’)匹配以字符串“line”结尾的名称
这种转变:
当应用于theis XML文档时:
- <greeting>
- <aaa>Hello</aaa>
- <bblineb>Good</bblineb>
- <ccc>Excellent</ccc>
- <dddline>Line</dddline>
- </greeting>
- <dddline>Line</dddline>
这个转换(使用匹配(name(),’.* line’)):
- <xsl:stylesheet version="2.0"
- xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
- xmlns:xs="http://www.w3.org/2001/XMLSchema">
- <xsl:output omit-xml-declaration="yes" indent="yes"/>
- <xsl:template match="*[matches(name(),'.*line')]">
- <xsl:copy-of select="."/>
- </xsl:template>
- <xsl:template match="*[not(matches(name(),'.*line'))]">
- <xsl:apply-templates select="node()[not(self::text())]"/>
- </xsl:template>
- </xsl:stylesheet>
- <bblineb>Good</bblineb>
- <dddline>Line</dddline>