xml – 在XSL中匹配子元素
我以为我在回答
this question时看到了一个错误,并指出了它.我被告知我不正确,我的答案后来被删除了.
我仍然没有看到我错了.因此,我在这里发帖,希望有人能解释我对我的误解. 我回答的答案解释了apply-templates的使用.它包含以下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> <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. 测试我的“更正”版本 如果我将最后一个模板替换为: <xsl:template match="*"> <!-- will be called twice --> <xsl:text>other element countered.
</xsl:text> </xsl:template> 根据我的回答,我得到: foo element encountered. other element countered. other element countered. 这似乎是正确的. 我希望我的问题不会破坏任何指导方针,但我看不出我错了,希望有人能够更充分地解释它. PS.我担心我对另一个问题的原始回复是作为答案发布的,而不是评论,因为我还没有足够的意见发表评论.我不确定最好的事情是做什么的……
这是正确的,根据
rules on the default priority of templates.模板匹配foo具有默认优先级0,一个匹配*具有默认优先级-0.5,但一个匹配xml / *具有默认优先级0.5. xml / *模板被认为比foo模板更具体,所以当它们匹配时它会获胜.
所以你是正确的,模板的匹配表达式需要是*而不是xml / *,但不是正确的原因 – 当当前节点是xml时,xml / *模板可以匹配apply-templates select =“*”,它将适用于任何所选元素(因为它们都是xml的子元素),除非有另一个显式优先级大于0.5的模板可以优先使用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |