xsl:变量 xsl:copy-of select

Mat*_*ntz 5 xslt

我有以下 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" select="msxsl:node-set($FirstPictureResultTreeFragment)/*"/>
        <xsl:value-of select="$FirstPicture/@attr"/>
        <!-- further operations on the $FirstPicture node -->
    </xsl:template>

    <xsl:template name="SelectFirstPicture">
        <xsl:param name="Pictures"/>
        <xsl:copy-of select="$Pictures[1]"/>
    </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

不好,在 XSLT 1.0 中不可能直接从模板输出节点,但是使用额外的变量至少不是不可能的。

Mar*_*nen 4

如果您愿意的话,可以使用 XSLT 1.0 处理器

    <xsl:variable name="FirstPicture">
        <xsl:copy-of select="Pictures[1]"/>
    </xsl:variable>
Run Code Online (Sandbox Code Playgroud)

该变量是一个结果树片段,在纯 XSLT 1.0 中您所能做的就是用copy-of(或value-of) 输出它。如果您想应用 XPath,您首先需要将结果树片段转换为节点集,大多数 XSLT 1.0 处理器都支持扩展功能,因此请尝试

    <xsl:variable name="FirstPictureRtf">
        <xsl:copy-of select="Pictures[1]"/>
    </xsl:variable>
    <xsl:variable name="FirstPicture" select="exsl:node-set(FirstPictureRtf)/Pictures/@attr">
Run Code Online (Sandbox Code Playgroud)

xmlns:exsl="http://exslt.org/common"您在样式表中定义的位置。

请注意,您需要检查您的 XSLT 1.0 处理器是否支持 EXSLT 扩展函数或另一个名称空间中的类似函数(例如各种 MSXML 版本都支持)。