2013-08-17 134 views
3

我是XSLT 2.0的新手。我對用戶定義的功能感興趣(<xsl:function)。特別是,我想使用UDF來使代碼更加模塊化和可讀。XSLT用戶定義函數

我有這樣的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的選項,如果我使它更復雜,整理這段代碼。這是否是一個好習慣?

+0

在XSLT 1.0不支持,只有2.0:https://www.w3.org/TR/xslt20/#stylesheet-functions – Andrew

回答

9

那麼你可以編寫一個函數在謂語

<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> 
+0

我在我的代碼稱爲這個例子。但我沒有找到方法java.lang.String.getLocaleName其中'getLocaleName'方法我實現。 – void

+0

請注意,這些僅在XSLT 2.0中受支持:https://www.w3.org/TR/xslt20/#stylesheet-functions – Andrew