【问题标题】:xslt moving child attribute to parentxslt 将子属性移动到父属性
【发布时间】:2015-07-29 14:53:04
【问题描述】:

输入:

    <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"&gt;to-content&lt;/xsl:attribute&gt;,因为它会抛出“如果先前的指令创建任何子级,在此处创建属性将失败。”警告然后错误。我理解如here 所述。有什么解决方法吗?

将 XSLT 2.0 与 Saxon 9 结合使用。(仍然掌握 XSLT/S.O. 的窍门)。对不起,如果这太宽泛了,但任何方向的任何帮助都将不胜感激。

【问题讨论】:

  • 考虑发布最小但完整的 XML、XSLT 示例、您想要的输出和您获得的输出,以便我们重现问题。您当前的 sn-p 是一个匹配 book 元素的单个模板,但甚至没有创建其中任何一个的副本,然后处理任何 chapter 子级,同样不复制任何子级,但随后创建属性 chunk。鉴于 sn-p 你只会输出没有多大意义的属性。
  • 已编辑问题。我的代码在这里没用。我正在创作这本书、章节和一切都很好。不在这里发帖,因为它很大。因此,任何帮助/想法将不胜感激。 :)

标签: xml xslt dita


【解决方案1】:

为了向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"/>

【讨论】:

  • 这很简单并且有效。需要进行一些编辑以集成到我的代码中,但非常感谢:)
【解决方案2】:

试试这个:

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 2018-07-24
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多