我有这个伪xml:
<list>
<entry id="1">
<item>Item 1</item>
<link ref="2"/>
</entry>
<entry id="2">
<item>Item 2</item>
</entry>
</list>
我想在由属性选择的模板中获取<item>
节点:
<xsl:template match="link">
<xsl:value-of select="/list/entry[@id=./@ref]/item"/>
</xsl:template>
当我手动输入/list/entry[@id='2']/item
时,它可以工作,但我需要它动态。当我调试它时,./@ref
(也只是@ref
)是2
的正确值。
我在这里错过了什么?
原因是:
<xsl:template match="link">
<xsl:value-of select="/list/entry[@id=./@ref]/item"/>
</xsl:template>
不起作用是因为 xPath 在 id
属性等于 ref
属性时尝试选择entry
。(您需要使用current()/@ref
。
但是,我建议使用 xsl:key
根据id
属性创建所有entry
元素的键......
XML 输入
<list>
<entry id="1">
<item>Item 1</item>
<link ref="2"/>
</entry>
<entry id="2">
<item>Item 2</item>
</entry>
</list>
XSLT 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="entries" match="entry" use="@id"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="link">
<test>
<xsl:value-of select="key('entries',@ref)/item"/>
</test>
</xsl:template>
</xsl:stylesheet>
XML 输出
<list>
<entry id="1">
<item>Item 1</item>
<test>Item 2</test>
</entry>
<entry id="2">
<item>Item 2</item>
</entry>
</list>