我以为我在这个问题的答案中看到了错误,并指出了这一点。有人告诉我我错了,我的答案后来被删除了。
我仍然不明白我是怎么错的。因此,我在这里发帖,希望有人能向我解释我的误解。
我回复的答案解释了应用模板的使用。它包含以下 XML 和 XSL,描述了如何匹配模板:
<!-- sample XML snippet -->
<xml>
<foo /><bar /><baz />
</xml>
<!-- sample XSLT snippet -->
<xsl:template match="xml">
<xsl:apply-templates select="*" /> <!-- three nodes selected here -->
</xsl:template>
<xsl:template match="foo"> <!-- will be called once -->
<xsl:text>foo element encountered</xsl:text>
</xsl:template>
<xsl:template match="xml/*"> <!-- will be called twice -->
<xsl:text>other element countered</xsl:text>
</xsl:template>
我的评论是最后一个模板应该是:
<xsl:template match="*"> <!-- will be called twice -->
<xsl:text>other element countered</xsl:text>
</xsl:template>
因为当前节点已经<xml>
有人告诉我:
不,xml/* 是一个匹配名为 xml 的元素的子元素的模式。
测试原始答案
但是,使用此 XML:
<xml>
<foo /><bar /><baz />
</xml>
还有这个 XSL 样式表(填写上面的代码片段):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="xml">
<xsl:apply-templates select="*" /> <!-- three nodes selected here -->
</xsl:template>
<xsl:template match="foo"> <!-- will be called once -->
<xsl:text>foo element encountered.
</xsl:text>
</xsl:template>
<xsl:template match="xml/*"> <!-- will be called twice -->
<xsl:text>other element countered.
</xsl:text>
</xsl:template>
</xsl:stylesheet>
我得到:
other element countered.
other element countered.
other element countered.
测试我的“更正”版本
If I replace the last template with:
<xsl:template match="*"> <!-- will be called twice -->
<xsl:text>other element countered.
</xsl:text>
</xsl:template>
as per my answer I get:
foo element encountered.
other element countered.
other element countered.
which would appear to be correct.
I hope my question doesn't break any guidelines, but I can't see that I'm wrong and am hoping someone can explain it more fully.
PS. I'm afraid my original response on the other question was posted as an answer, not a comment, as I don't have enough points to post comments yet. I wasn't sure what the best thing was to do...