将XSLT模板应用于从函数返回的字符串

时间:2014-02-19 21:54:04

标签: xml templates xslt xslt-1.0 apply-templates

(这里的所有代码都是从原始版本中简化而来)

我的公司有一个在XSLT(1.0)中使用的函数,它从我们的文件系统中的文件中返回内容。我需要能够使用apply-templates解析函数的返回。请考虑以下示例:

主XML文件:

<exhibit>
    <exhibitTitle>Exhibit</exhibitTitle>
    <linkedAsset href="path/to/file.xml" />
</exhibit>

外部XML文件:

<externalAsset editable="true" id="U10250926378W6C">
    <img src="path/to/image.png" />
    <caption>Some default image</caption>
<externalAsset>

我尝试将以下XSLT应用于主XML文件

XSLT:

<xsl:template match="linkedAsset">
    <xsl:apply-templates select="cus:getFileByUri(./@href)" />
</xsl:template>

<xsl:template match="img">
    <xsl:text>|-- Begin Image Source --|</xsl:text>
    <xsl:value-of select="./src" />
    </xsl:text>|-- End Image Source --|</xsl:text>
</xsl:template>

结果只是“一些默认图像”。

为了确保我获得XML结构,而不仅仅是我尝试的所有节点(或其他)的值:

<xsl:template match="linkedAsset">
    <xsl:copy-of select="cus:getFileByUri(./@href)" />
</xsl:template>

返回了原始的外部XML文件结构:

<externalAsset editable="true" id="U10250926378W6C">
    <img src="path/to/image.png" />
    <caption>Some default image</caption>
<externalAsset>

我也尝试过:

<xsl:template match="linkedAsset">
    <xsl:value-of select="cus:getFileByUri(./@href)//img/@src" />
</xsl:template>

按预期返回“path / to / image.png”。

最后,根据this question的答案,我尝试了以下XSLT:

<xsl:template match="linkedAsset">
    <xsl:call-template name="renderExternal">
        <xsl:with-param name="asset" select="cus:getFileByUri(./@href)" />
    </xsl:call-template>
</xsl:template>

<xsl:template name="renderExternal">
    <xsl:param name="asset" select="." />
    <xsl:apply-templates select="$asset" />
</xsl:template>

输出与原始apply-template相同。

有没有办法将apply-templates应用于函数返回的值?我可以清楚地将字符串发送到copy-ofvalue-of,甚至可以在其上执行xpath;我可以直接将其用于apply-templates吗?


CHOSEN ANSWER的解释

事实证明,我的问题的解决方案非常具体(我将模板应用于匹配相同模板的节点,而且从我提供的代码的简化版本中不能清楚)。我真的在这个上获得了-1。 无论如何,我觉得keshlam的回答对将来访问这个问题的人最有帮助,因为它回答了我认为我的问题。

1 个答案:

答案 0 :(得分:1)

要对其执行apply-templates,您的扩展必须将XML返回到已解析形式的样式表(通常是DOM树或NodeIterator)。在XSLT 1.0中,您可能必须应用exslt:node-set()扩展函数或处理器的等价物,用于处理临时树和节点集之间的阻抗不匹配(xsl:apply-templates在节点集上运行)。

写入和注册扩展的细节可能因处理器而异。例如,如果您正在使用Xalan-J,请参阅https://xml.apache.org/xalan-j/extensions.html