xml - XSLT 用户定义函数

标签 xml xslt xslt-2.0

我是 XSLT 2.0 的新手。我对用户定义的函数 ( <xsl:function) 很感兴趣。特别是,我想使用 UDF 使代码更加模块化和可读性更好。

我有这个 xsl:

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet
   version="2.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
    <xsl:variable name="stopwords"
        select="document('stopwords.xml')//w/string()"/>
             <wordcount>
                <xsl:for-each-group group-by="." select="
                    for $w in //text()/tokenize(., '\W+')[not(.=$stopwords)] return $w">
                    <xsl:sort select="count(current-group())" order="descending"/>            
                    <word word="{current-grouping-key()}" frequency="{count(current-group())}"/>
                </xsl:for-each-group>
             </wordcount>
</xsl:template>
</xsl:stylesheet>

可以想添加更多的条件测试(例如,排除数字)到 for $w in //text()/tokenize(., '\W+')[not(.=$stopwords)] 但代码会变得困惑。

如果我使它更复杂,UDF 是否是整理该部分代码的选项。这样做是好的做法吗?

最佳答案

那么你可以写一个函数在谓词中使用

<xsl:function name="mf:check" as="xs:boolean">
  <xsl:param name="input" as="xs:string"/>
  <xsl:sequence select="not($input = $stopwords) and not(matches($input, '^[0-9]+$'))"/>
</xsl:function>

并在您的代码中使用它,例如

<xsl:stylesheet
   version="2.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:xs="http://www.w3.org/2001/XMLSchema"
   xmlns:mf="http://example.com/mf"
   exclude-result-prefixes="mf xs">
<xsl:output method="xml" indent="yes"/>

    <xsl:function name="mf:check" as="xs:boolean">
      <xsl:param name="input" as="xs:string"/>
      <xsl:sequence select="not($input = $stopwords) and not(matches($input, '^[0-9]+$'))"/>
    </xsl:function>

    <xsl:variable name="stopwords"
        select="document('stopwords.xml')//w/string()"/>

    <xsl:template match="/">
        <wordcount>
            <xsl:for-each-group group-by="." select="
                for $w in //text()/tokenize(., '\W+')[mf:check(.)] return $w">
                <xsl:sort select="count(current-group())" order="descending"/>            
                <word word="{current-grouping-key()}" frequency="{count(current-group())}"/>
            </xsl:for-each-group>
        </wordcount>
    </xsl:template>
</xsl:stylesheet>

关于xml - XSLT 用户定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18289265/

相关文章:

android - 连接 PhoneGap 与本地主机网络服务

javascript - 从php->mysql节点中xml的深度

xml - XSLT 以不同的 xml 读取顺序应用模板

xml - XSLT 2.0 将 xml 中所有出现的 'true/false' 替换为 'yes/no'

xml - xsl : how to split strings?

python - 通过其相邻值推导 html 元素

c# - 将对象保存到没有序列化属性的文件的最简单方法是什么?

css - RSS 不在 Chrome 中显示

css - XSL 无法用 Firefox 解析

xslt - 使用 XSLT/XPath 2.0 以某种方式输出值