xslt 将子属性移动到父级

xslt moving child attribute to parent

输入:

    <book>
     <chapter href="..">
      <topicref chunk="to-content" href"..">

      </topicref>
      <topicref chunk="to-content" href"..">

      </topicref>
     </chapter>
    </book>    

输出:

    <book>
     <chapter chunk="to-content" href="..">
      <topicref href"..">

      </topicref>
      <topicref href"..">

      </topicref>
     </chapter>
    </book> 

我不能使用 xsl:attribute name="chunk">to-content</xsl:attribute>,因为它会抛出 "creating an attribute here will fail if previous instructions create any children." 警告然后出错。我的理解是 here 所描述的。有什么解决方法吗?

将 XSLT 2.0 与 Saxon 9 结合使用。(刚刚掌握 XSLT/ S.O。仍然如此)。抱歉,如果这太宽泛了,但我们将不胜感激任何方向的帮助。

为了向 chapter 元素添加属性,最好有一个与 chapter 元素相匹配的模板 - 按照以下行:

<xsl:template match="chapter">
    <xsl:copy>
        <xsl:attribute name="chunk">to-content</xsl:attribute>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

同样,要从 topicref 中删除 chunk 属性:

<xsl:template match="topicref/@chunk"/>

试试这个:

<xsl:template match="/">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="chapter">
  <xsl:copy>
    <!-- If the chapter contains a topicref with chunk="to-content", set chunk to-content on the chapter unless it's already there.-->
    <xsl:if test=".//topicref/@chunk = 'to-content' and not(@chunk='to-content')">
      <xsl:attribute name="chunk">to-content</xsl:attribute>
    </xsl:if>
    <!-- Copy all chapter attributes -->
    <xsl:copy-of select="@*"/>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

<xsl:template match="topicref">
  <xsl:copy>
    <!-- Copy every attribute except chunk="to-content" -->
    <xsl:copy-of select="@*[not(name() = 'chunk' and . = 'to-content')]"/>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

<xsl:template match="*">
  <xsl:copy>
    <xsl:copy-of select="@*"/>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>