2011-08-16 49 views
2

XML:如何重號過濾元件設置

<?xml version="1.0" encoding="utf-8"?> 
<book> 
    <chapter> 
     <section name="a">...</section> 
     <section name="b">...</section> 
     <section name="c">...</section> 
     <section name="d">...</section> 
     <section name="e">...</section> 
     ... 
    </chapter> 
    <appendix> 
     <section name="reference">...</section> 
    </appendix> 
</book> 

您好,我想輸出的所有sectionschapterappendix節點。附錄中的部分將被打印出來。但是並不是所有章節都允許打印出,它們依賴於一些外部條件(如果段名在允許從java應用程序中傳入的列表中)。

而且sectionschapter下應與正確序列號輸出前部分的名稱看起來像下面這樣:

期望的結果

  1. b ...
  2. d .. 。

(這意味着部分a,c,e被過濾掉)

我的問題是我如何能夠產生//chapter/section以上所需的輸出?任何提示或幫助是高度讚賞

我的XSL:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ex="http://example.com/namespace" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" indent="yes"/> 

    <xsl:param name="validChapters" /> 

    <xsl:function name="ex:isValidChapter" as="xs:boolean"> 
     <xsl:param name="str-in" as="xs:string"/> 
     <xsl:choose> 
      <xsl:when test="contains($validChapters, $str-in)"> 
       <xsl:sequence select="true()" /> 
      </xsl:when> 
      <xsl:otherwise> 
       <xsl:sequence select="false()" /> 
      </xsl:otherwise> 
     </xsl:choose> 
    </xsl:function> 

    <xsl:template match="/"> 
     <xsl:apply-templates select="chapter" /> 
     <xsl:apply-templates select="appendix" /> 
    </xsl:template> 

    <xsl:template match="chapter"> 
     ... 
     <xsl:apply-templates select="section" /> 
    </xsl:template> 

    <xsl:template match="appendix"> 
     ... 
     <xsl:apply-templates select="section" /> 
    </xsl:template> 

    <xsl:template match="section"> 
     ... 
     <xsl:apply-templates /> 
    </xsl:template> 

    <xsl:template match="//chapter/section"> 
     <xsl:if test="ex:isValidChapter(@name)"> 
      <fo:block> 
       <xsl:number format="1."/> 
       <xsl:value-of select="@name" /> 
      </fo:block> 
      <xsl:apply-templates /> 
     </xsl:if> 
    </xsl:template> 

    ... 
</xsl:stylesheet> 
+0

用示例XML數據和所需輸出解釋更清楚。 –

+0

「允許列表」存儲在哪裏? –

+0

允許列表從java應用程序傳入,並以逗號分隔字符串的形式使用包含函數 –

回答

0

答案是簡單地提供一個count=屬性您<xsl:number>指令:因此,在編號的部分

 <xsl:number format="1." count="section[ex:isValidChapter(@name)]"/> 

,只有「有效」的部分纔會被計數,所以編號是正確的。

還要注意的是,你需要修改你的模板,上面寫着:

<xsl:template match="/"> 
    <xsl:apply-templates select="chapter" /> 

因爲<chapter>是不是根節點的孩子。 (它是文檔元素的子節點,<book>

<xsl:template match="/book"> 
    <xsl:apply-templates select="chapter" /> 

此外,您的函數不需要選擇/何時/否則將布爾結果轉換爲布爾值。它可以縮寫爲:

<xsl:function name="ex:isValidChapter" as="xs:boolean"> 
    <xsl:param name="str-in" as="xs:string"/> 
    <xsl:sequence select="contains($validChapters, $str-in)"/> 
</xsl:function>