使用变量存储和输出属性

Haf*_*ger 2 xslt

如果有一个很大的“ xsl:choose”块,我需要在其中为不同的元素设置许多已定义的属性集。

我真的不喜欢在“选择”的每个分支内重复定义属性集。因此,我想使用包含这些属性的变量。易于维护且出错的空间更少...

到目前为止,我还无法调出属性节点吗?我以为它们只是一个节点集,所以复制就可以解决问题。
但这对我的输出没有任何帮助。
这是因为属性节点不是真正的子级吗?
但是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>
Run Code Online (Sandbox Code Playgroud)

如果在XLST 1.0中无法做到这一点,那么2.0可以做到这一点吗?

Dim*_*hev 5

<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>
Run Code Online (Sandbox Code Playgroud)

您需要选择所需的属性-而不是将其内容复制到变量的主体中。

请记住:只要有可能,请始终尝试在-的select属性中指定XPath表达式,xsl:variable避免在其主体中复制内容。

解决方案

只需使用

<xsl:variable name="attributes_body" select="@chapter | @id"> 
Run Code Online (Sandbox Code Playgroud)

这是一个完整的示例

<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>
Run Code Online (Sandbox Code Playgroud)

当应用于此

<x>
 <a m="1" n="2" p="3">zzz</a>
</x>
Run Code Online (Sandbox Code Playgroud)

产生

 <newEntry m="1" n="2">zzz</newEntry>
Run Code Online (Sandbox Code Playgroud)