xslt - 使用变量来存储和输出属性

标签 xslt

如果有一个大的“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:variableselect 属性中指定 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/

相关文章:

xslt - XSL:如何在for-each中打印迭代的节点

xml - Altova XMLSpy XSLT 转换器和 Saxon XSLT 转换器之间有什么区别?

xml - XSLT 合并节点

xml - 如何使用 XSLT 对 XML 的子元素进行排序

xml - 使用 XSLT 排除 XML 空节点

xml - XPath - 测试是否至少有一个节点具有给定值

c# - 转换过程中的 XSLT 问题

java - javax.xml.transform 使用什么处理器?

XSLT:根据来自其他节点的值的总和进行排序

xslt - 在 XSL 中进行双 channel ?