在XSLT中使用RegEx

aba*_*hev 4 regex xml xslt

我需要解析Visual Studio自动生成的XML文档来创建报告.我决定使用XSLT,但我很新,需要帮助.常用模板是:

<doc>
  <members>
    <member name="F:MyNamespace">
      <summary>Some text</summary>
    </member> 
  </members>
</doc>
Run Code Online (Sandbox Code Playgroud)

我想隔离名称以某些单词开头的成员,例如P:Interfaces.Core.我决定在select语句中使用RegExp.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:fn="http://www.w3.org/TR/xpath-functions/">
    <xsl:template match="/" >
        <html xmlns="http://www.w3.org/1999/xhtml">
            <body style="font-family:Tahoma">
                <p>Interfaces list:</p>
                <table>
                    <xsl:for-each select="doc/members/member">
                        <xsl:sort order="ascending" />
                        <xsl:value-of select="fn:matches(., 'P\..+')" />
                        <br />
                    </xsl:for-each>
                </table>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

为什么我收到错误:

命名空间http://www.w3.org/TR/xpath-functions不包含任何函数>

我哪里错了?我在示例中找到了这样的代码,包括w3c.org!

Dim*_*hev 8

如果您使用Visual Studio X执行转换,其中X不大于2008,则将由XSLT 1.0处理器(.NET XslCompiledTransformXslTransform)处理.XSLT 1.0使用XPath 1.0,而不是XPath 2.0及其F&O(功能和操作),它仅在去年成为W3推荐标准.

您有两种选择:

  1. 使用兼容的XSLT 2.0处理器.如果您希望保留在.NET平台中,那么一个合适的选择是Saxon.NET

  2. 只需使用XPath 1.0功能 starts-with(),这足以解决当前的问题.
    表达式:starts-with(., 'P:Interfaces')被评估以true()如果上下文节点的字符串值与字符串开始"P:接口"和false()其他.

另一个可能对这种类型的处理有用的Xpath 1.0函数就是函数contains().

ends-with()可以通过以下方式在XPath 1.0中模拟Xpath的2.0函数:

ends-with(s1, s2)==== substring(s1,string-length(s1) - string-length(s2)+1)= s2

其中" ==="表示"等同于".

这里我们还使用了XPath 1.0函数substring()string-length().