我有以下 XML:
<?xml version="1.0" encoding="UTF-8"?>
<XmlTest>
<Pictures attr="Pic1">Picture 1</Pictures>
<Pictures attr="Pic2">Picture 2</Pictures>
<Pictures attr="Pic3">Picture 3</Pictures>
</XmlTest>
Run Code Online (Sandbox Code Playgroud)
虽然此 XSL 执行了预期的操作(输出第一张图片的属性):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/XmlTest">
<xsl:variable name="FirstPicture" select="Pictures[1]">
</xsl:variable>
<xsl:value-of select="$FirstPicture/@attr"/>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
似乎不可能在使用 xsl:copy-of 的变量声明中做同样的事情:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="/XmlTest">
<xsl:variable name="FirstPicture">
<xsl:copy-of select="Pictures[1]"/>
</xsl:variable>
<xsl:value-of select="$FirstPicture/@attr"/>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
好奇:如果我在第二个例子中只选择“$FirstPicture”而不是“$FirstPicture/@attr”,它会按预期输出图片1的文本节点......
在大家建议我重写代码之前:这只是一个简化的测试,我的真正目的是使用命名模板将一个节点选择到变量 FirstPicture 中,并将其重用于进一步的选择。
我希望有人可以帮助我理解这种行为,或者可以向我建议一种正确的方法来选择带有可以轻松重用的代码的节点(在我的实际应用程序中,第一个节点是第一个节点的决定很复杂)。谢谢。
编辑(感谢 Martin Honnen): 这是我的工作解决方案示例(另外使用一个单独的模板来选择请求的图片节点),使用 MS XSLT 处理器:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
version="1.0">
<xsl:template match="/XmlTest">
<xsl:variable name="FirstPictureResultTreeFragment">
<xsl:call-template name="SelectFirstPicture">
<xsl:with-param name="Pictures" select="Pictures" />
</xsl:call-template>
</xsl:variable>
<xsl:variable name="FirstPicture" …Run Code Online (Sandbox Code Playgroud) xslt ×1