我想替换除最内层子节点之外的给定节点的节点名称?

时间:2017-08-29 07:28:07

标签: xml xslt xpath

输入XML

<topicref outputclass="Dx:Appendix" href="appendix_topic_a.dita">
   <topicref outputclass="Dx:Appendix" href="appendix_topic_b.dita">
      <topicref outputclass="Dx:Appendix" href="appendix_topic_c.dita"/>
   </topicref>
   <topicref outputclass="Dx:Appendix" href="appendix_topic_d.dita">
     <topicref outputclass="Dx:Appendix" href="appendix_topic_e.dita"/>
   </topicref>    
</topicref>
<topicref outputclass="Dx:Appendix" href="appendix_topic_f.dita"/>

输出

<appendix class="Dx:Appendix" href="appendix_topic_a.dita">
   <appendix class="Dx:Appendix" href="appendix_topic_b.dita">
      <topicref class="Dx:Appendix" href="appendix_topic_c.dita"/>
   </appendix>
   <appendix class="Dx:Appendix" href="appendix_topic_d.dita">
     <topicref class="Dx:Appendix" href="appendix_topic_e.dita"/>
   </appendix>    
</appendix>
<appendix class="Dx:Appendix" href="appendix_topic_f.dita"/>

所以基本上我需要将节点<topicref>的名称更改为<appendix>,如果它不是最里面的<topicref>。如果它是一个独立的节点,例如<topicref> href="appendix_topic_f.dita"的情况,我需要将其更改为<appendix>,这是一个自关闭标记。 此外,必须将属性名称outputclass更改为class,使其值保持不变。

1 个答案:

答案 0 :(得分:0)

如果我冒昧地重申您的要求:更改topicref的名称,如果:

  • 小时候有另一个topicref;
  • 其父级不是另一个topicref
然后我到达:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="topicref[topicref or not(parent::topicref)]">
    <appendix>          
        <xsl:apply-templates select="@*|node()"/>
    </appendix>         
</xsl:template>

</xsl:stylesheet>

应用于以下格式良好的测试输入:

<强> XML

<root>
    <topicref outputclass="Dx:Appendix" href="appendix_topic_a.dita">
        <topicref outputclass="Dx:Appendix" href="appendix_topic_b.dita">
            <topicref outputclass="Dx:Appendix" href="appendix_topic_c.dita"/>
        </topicref>
        <topicref outputclass="Dx:Appendix" href="appendix_topic_d.dita">
            <topicref outputclass="Dx:Appendix" href="appendix_topic_e.dita"/>
        </topicref>
    </topicref>
    <topicref outputclass="Dx:Appendix" href="appendix_topic_f.dita"/>
</root>

结果将是:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <appendix outputclass="Dx:Appendix" href="appendix_topic_a.dita">
    <appendix outputclass="Dx:Appendix" href="appendix_topic_b.dita">
      <topicref outputclass="Dx:Appendix" href="appendix_topic_c.dita"/>
    </appendix>
    <appendix outputclass="Dx:Appendix" href="appendix_topic_d.dita">
      <topicref outputclass="Dx:Appendix" href="appendix_topic_e.dita"/>
    </appendix>
  </appendix>
  <appendix outputclass="Dx:Appendix" href="appendix_topic_f.dita"/>
</root>