【发布时间】:2012-12-13 17:01:53
【问题描述】:
我有以下 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>
虽然此 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>
似乎不可能在使用 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>
好奇: 如果我在第二个示例中只选择“$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>
不好,在 XSLT 1.0 中不能直接从模板输出节点,但使用额外的变量至少不是不可能的。
【问题讨论】:
-
为什么要执行复制子树的昂贵操作?副本中的属性将与原始属性相同。只需使用选择表单 - 效率更高。并且您避免了与结果树片段相关的 XSLT 1.0 限制。
-
处理我的例子,你是绝对正确的,选择完整的节点集将是开销。在我的实际应用程序中,我不只是想选择单个属性,而是需要在该节点上提交进一步的操作,例如选择子节点和调用其他模板。我想在我的 xsl 中的几个地方使用它而不复制任何代码。
标签: xslt