2011-01-07 31 views
3

考慮下面的XML片段:在XSL中可以匹配「none」嗎?

<foo> 
    <bar>1</bar> 
    <bar>2</bar> 
    <bar>3</bar> 
</foo> 

下面的XSL應該工作:

<xsl:template match="/"> 
    <xsl:apply-templates 
    mode="items" 
    select="bar" /> 
</xsl:template> 

<xsl:template mode="items" match="bar"> 
    <xsl:value-of select="." /> 
</xsl:template> 

有沒有一種方法,我可以使用類似的格式,以這個應用模板,當有沒有<bar/>實體?例如:

<xsl:template match="/"> 
    <xsl:apply-templates 
    mode="items" 
    select="bar" /> 
</xsl:template> 

<xsl:template mode="items" match="bar"> 
    <xsl:value-of select="." /> 
</xsl:template> 

<xsl:template mode="items" match="none()"> 
    There are no items. 
</xsl:template> 
+0

問得好,+1。查看我對exlanation的回答以及僅使用模板並且沒有顯式條件XSLT指令的完整簡短解決方案。 :) –

回答

2

人們還可以使用這個模式,以避免額外的選:

<xsl:template match="/*"> 
    <xsl:apply-templates select="bar" mode="items"/> 
    <xsl:apply-templates select="(.)[not(bar)]" mode="show-absence-message"/> 
</xsl:template> 

<xsl:template match="bar" mode="items"> 
    <xsl:value-of select="."/> 
</xsl:template> 

<xsl:template match="/*" mode="show-absence-message"> 
    There are no items. 
</xsl:template> 
+0

工作完美!謝謝!! –

1

沒有,當你有apply-templates select="bar"和上下文節點沒有任何bar子元素則沒有節點進行處理,因此不應用模板。但是,您可以將使用應用模板的模板中的代碼更改爲

<xsl:choose> 
    <xsl:when test="bar"> 
     <xsl:apply-templates select="bar"/> 
    </xsl:when> 
    <xsl:otherwise>There are not items.</xsl:otherwise> 
    </xsl:choose> 
5

是的。

但邏輯應該是:

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

<xsl:template match="foo[not(bar)]"> 
    There are no items. 
</xsl:template> 

注:這是其具有或不具有bar孩子foo元素。

+0

+1。更好的答案。 – Flack

+0

Upvoted,但我已經與@ Flack的答案一樣,有時不能使用父上下文。 –

+0

@digitala:沒問題。但**總是可以使用這種模式匹配**。 @ Flack的答案使用**推式**('xsl:apply-tempates/@ select')和模式('xsl:apply-tempates/@ mode')代替這種**拉式**。 – 2011-01-07 15:59:10

0

考慮下面的XML片段:

<foo> 
    <bar>1</bar> 
    <bar>2</bar> 
    <bar>3</bar> 
</foo> 

下面的XSL應該工作:

<xsl:template match="/"> 
<xsl:apply-templates mode="items" select="bar" /> 
</xsl:template> 

<xsl:template mode="items" match="bar"> 
<xsl:value-of select="." /> 
</xsl:template> 

不,上面的<xsl:apply-templates>根本不選擇任何節點

有沒有一種方法,我可以使用類似的 格式這個時候有沒有實體應用模板 ?

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

    <xsl:template match="/*[not(bar)]"> 
     No <bar/> s. 
    </xsl:template> 

    <xsl:template match="/*[bar]"> 
     <xsl:value-of select="count(bar)"/> <bar/> s. 
    </xsl:template> 
</xsl:stylesheet> 

當施加到所提供的XML文檔

<foo> 
    <bar>1</bar> 
    <bar>2</bar> 
    <bar>3</bar> 
</foo> 

結果是

3<bar/> s. 

當應用到這個XML文檔

<foo> 
    <baz>1</baz> 
    <baz>2</baz> 
    <baz>3</baz> 
</foo> 

結果是

No <bar/> s. 
相關問題