我有以下 xsl 转换输入:
<root>
<Section>
<Section>
<Type>Table</Type>
</Section>
</Section>
</root>
我正在尝试应用模板,并仅匹配当前的部分节点,但匹配 xsl:template
上的表达式也将匹配任何子部分。
有没有办法限制只匹配当前节点?
我正在应用此 xsl 样式表:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/*">
<output>
<xsl:apply-templates select="Section" />
</output>
</xsl:template>
<xsl:template match="Section[Type]">
<xsl:value-of select="." />
</xsl:template>
<xsl:template match="text()" />
</xsl:stylesheet>
输出为:
<output>
Table
</output>
模板匹配Section[Type]
与该小节匹配,但我正在寻找的结果是 <xsl:apply-templates select="Section" />
时被调用时,不应匹配任何内容,因为当前部分没有 Type
元素。
或者,对于这种情况我是否必须使用调用模板?
另一个选项是匹配部分/类型,但我想避免使用 ..
为了返回父节点,只是为了代码清晰起见。
最佳答案
您遇到的困惑是由于 XSLT 的 built-in templates ,当 XSLT 处理器在 XSLT 文件中找不到匹配的模板时应用。就你而言,当你这样做时......
<xsl:apply-templates select="Section" />
它将寻找与第一个 Section
匹配的模板。 ,但是您的 XSLT 中没有匹配的模板,因为您拥有的模板仅匹配 Section
有子元素的元素 Type
。然后内置模板就会启动,这实际上就是这样..
<xsl:template match="*|/">
<xsl:apply-templates/>
</xsl:template>
也就是说,它会应用与子元素匹配的模板;您的子部分。
解决方案是为 Section
添加匹配模板在您的 XSLT 中
<xsl:template match="Section" />
因为这不是用条件量化的,所以它的优先级低于匹配 Section[Type]
的优先级你应该只有一个这样的Section
在您的 XSLT 中。
尝试这个 XSLT
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/*">
<output>
<xsl:apply-templates select="Section" />
</output>
</xsl:template>
<xsl:template match="Section" />
<xsl:template match="Section[Type]">
<xsl:value-of select="." />
</xsl:template>
<xsl:template match="text()" />
</xsl:stylesheet>
应用于您的 XML,它仅输出 <output/>
,但如果你要把它应用到这个......
<root>
<Section>
<Type>Table</Type>
</Section>
</root>
输出将是这样的...
<output>
Table
</output>
您可以在 http://www.w3.org/TR/xslt#conflict 阅读有关模板优先级的信息。
关于xml - 如何在xsl模板规则中仅匹配当前节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39777329/