给出以下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>
当没有 <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 :(得分:5)
但逻辑应该是:
<xsl:template match="foo">
<xsl:apply-templates select="bar"/>
</xsl:template>
<xsl:template match="foo[not(bar)]">
There are no items.
</xsl:template>
注意: foo
元素是否有bar
个孩子。
答案 1 :(得分: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>
答案 2 :(得分:1)
不,当您有apply-templates select="bar"
并且上下文节点没有任何bar
子元素时,则不会处理任何节点,因此不会应用任何模板。但是,您可以在执行apply-templates的模板中更改代码,例如
<xsl:choose>
<xsl:when test="bar">
<xsl:apply-templates select="bar"/>
</xsl:when>
<xsl:otherwise>There are not items.</xsl:otherwise>
</xsl:choose>
答案 3 :(得分: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.