如果有一个大的“xsl:choose” block ,我需要在不同的元素上设置许多已定义的属性集。
我真的不喜欢在“选择”的每个分支中重复定义属性集。 所以我想使用包含这些属性的变量。 维护起来更容易,出错的空间也更少......
到目前为止我还没能把属性节点调用出来?
我认为它们只是一个节点集,所以复制就可以了。
但这没有给我任何输出。
这是因为属性节点并不是真正的子节点吗?
但 XSLT 1.O 不允许我直接解决它们... <xsl:copy-of select="$attributes_body/@*/>
返回错误
这是样式表片段(从原始版本减少)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="list">
<xsl:for-each select="figure">
<xsl:variable name="attributes_body">
<xsl:attribute name="chapter"><xsl:value-of select="@chapter"/></xsl:attribute>
<xsl:attribute name="id"><xsl:value-of select="@id"/></xsl:attribute>
</xsl:variable>
<xsl:variable name="attributes_other">
<xsl:attribute name="chapter"><xsl:value-of select="@book"/></xsl:attribute>
<xsl:attribute name="id"><xsl:value-of select="@id"/></xsl:attribute>
</xsl:variable>
<xsl:choose>
<xsl:when test="ancestor::body">
<xsl:element name="entry">
<xsl:copy-of select="$attributes_body"/>
<xsl:text>Body fig</xsl:text>
</xsl:element>
</xsl:when>
<xsl:otherwise>
<xsl:element name="entry">
<xsl:copy-of select="$attributes_other"/>
<xsl:text>other fig</xsl:text>
</xsl:element>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
如果这在 XLST 1.0 中无法完成,那么 2.0 也能做到吗?
最佳答案
<xsl:variable name="attributes_body"> <xsl:attribute name="chapter"><xsl:value-of select="@chapter"/></xsl:attribute> <xsl:attribute name="id"><xsl:value-of select="@id"/></xsl:attribute> </xsl:variable>
您需要选择想要的属性——而不是将它们的内容复制到变量的主体中。
记住:只要有可能,请始终尝试在 xsl:variable
的 select
属性中指定 XPath 表达式——避免将内容复制到它的 body 。
解决方案:
只需使用:
<xsl:variable name="attributes_body" select="@chapter | @id">
这是一个完整的示例:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="x/a">
<xsl:variable name="vAttribs" select="@m | @n"/>
<newEntry>
<xsl:copy-of select="$vAttribs"/>
<xsl:value-of select="."/>
</newEntry>
</xsl:template>
</xsl:stylesheet>
应用于此时:
<x>
<a m="1" n="2" p="3">zzz</a>
</x>
产生:
<newEntry m="1" n="2">zzz</newEntry>
关于xslt - 使用变量来存储和输出属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9785525/