2011-10-28 30 views
1

我想選擇給定ID的所有節點,但可能以附加數字結束。我怎樣才能做到這一點?ID以變量結尾的選擇列表

例子:

<group id="list"> 
<group id="list1"> 
<group id="list2"> 
<group id="map"> 
<group id="map1"> 

聲明林有現在:

<xsl:variable name="rule"> 
<data> 
    <node>list</node> 
    <node>map</node> 
</data> 
</xsl:variable> 

<xsl:template match="/"> 
    <xsl:apply-templates select=".//group[ @id = exslt:node-set($rule)/data/node]"/> 
</xsl:template> 

,並只允許我在 「規則」 列表中指定的節點上運行。 [XSLT v1.0]

請指教。

+2

XSLT 1.0或2.0? –

回答

1

I. XSLT 1.0溶液:

這種變換:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

<xsl:param name="pIds"> 
    <id>list</id> 
    <id>map</id> 
</xsl:param> 

<xsl:variable name="vIds" select= 
    "document('')/*/xsl:param[@name='pIds']/*"/> 

<xsl:template match="group"> 
    <xsl:if test= 
    "$vIds[. = current()/@id 
     or 
     starts-with(current()/@id, .) 
     and 
     substring-after(current()/@id, .) 
     = 
     floor(substring-after(current()/@id, .)) 
     ] 
    "> 
    <!-- Processing here: --> 
    <xsl:copy-of select="."/> 
    </xsl:if> 
</xsl:template> 
</xsl:stylesheet> 

當此XML文檔上施加:

<t> 
<group id="list"/> 
<group id="list1"/> 
<group id="listX"/> 
<group id="list2"/> 
<group id="map"/> 
<group id="map123Z"/> 
<group id="map1"/> 
</t> 

處理(在該例子中份)完全匹配節點

<group id="list"/> 
<group id="list1"/> 
<group id="list2"/> 
<group id="map"/> 
<group id="map1"/> 

說明

  1. 使用標準的XPath功能starts-with()substring-after()floor()

  2. 一個簡單的測試,如果字符串是可澆注到一個整數是:floor($s) = $s

II。 XSLT 2.0溶液:

<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:param name="pIds" select="'list', 'map'"/> 

<xsl:variable name="vIds" select= 
    "document('')/*/xsl:param[@name='pIds']/*"/> 

<xsl:template match= 
"group 
    [@id = $pIds 
    or 
    $pIds 
     [starts-with(current()/@id, .) 
    and 
     substring-after(current()/@id, .) 
     castable as 
     xs:integer 
     ] 
    ] 
"> 
    <!-- Processing here: --> 
    <xsl:copy-of select="."/> 
</xsl:template> 
</xsl:stylesheet> 

說明:該解決方案是相當類似的XSLT 1.0溶液具有以下主要區別:

  1. 在XSLT 2.0它被允許具有可變/參數引用匹配模式。使用這個我們避免了模板主體內的<xsl:if>

  2. 我們定義參數以包含所需字符串的序列。

  3. 我們使用標準的XPath 2.0運營商castable as