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>

有人告诉我:

No,xml/* is a pattern that matches child elements of an element with
the name 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.&#xa;</xsl:text>
</xsl:template>

<xsl:template match="xml/*"> <!-- will be called twice -->
  <xsl:text>other element countered.&#xa;</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.&#xa;</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的模板可以优先使用.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念
xml文件介绍及使用
xml编程(一)-xml语法
XML文件结构和基本语法
第2章 包装类
XML入门的常见问题(二)
Java对象的强、软、弱和虚引用
JS解析XML文件和XML字符串详解
java中枚举的详细使用介绍
了解Xml格式
XML入门的常见问题(四)
深入SQLite多线程的使用总结详解
PlayFramework完整实现一个APP(一)
XML和YAML的使用方法
XML轻松学习总节篇