2017-08-17 99 views
0

我在下面的表單中有我的xml內容,其中附錄可以有任何no。的子女也是如此。xslt如何遞歸地更改子節點的標記名稱

<topicref outputclass="Dx:Appendix" href="AppendixA-test.dita"> 
    <topicref outputclass="Dx:Appendix" href="AppendixA-sub-test.dita"/> 
    </topicref> 
    <topicref outputclass="Dx:Appendix" href="AppendixB-test.dita"/> 

現在我想我輸出XML看起來像這樣:

<appendix href="AppendixA-test.dita"> 
     <topicref href="AppendixA-sub-test.dita"/> 
    </appendix> 
    <appendix href="AppendixB-test.dita"/> 
+0

一個例子是不夠的:p用言語解釋所需的邏輯。 –

回答

0

這是一個XSLT-1.0解決方案:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <!-- copy all nodes except those more specific --> 
    <xsl:template match="node()|@*"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()|@*" /> 
    </xsl:copy> 
    </xsl:template> 

    <!-- modify all "topicref" nodes except those more specific --> 
    <xsl:template match="topicref"> 
    <xsl:element name="appendix"> 
     <xsl:apply-templates select="node()|@href" /> 
    </xsl:element> 
    </xsl:template> 

    <!-- do not modify the names of "topicref" elements with "topicref" parents" --> 
    <xsl:template match="topicref[parent::topicref]"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()|@href" /> 
    </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet> 
+0

你可以製作第一個模板match =「topicref [not(parent :: topicref)]」'並且消除第二個模板。如果這是預期的邏輯。 –

+0

@ michael.hor257k:我用兩個(而不是三個)模板測試了它,問題是複製了'topicref'的'outputclass'屬性。所以,無論如何,我需要第二個/第三個模板......我也想知道預期的結構,但沒有進一步的信息,這是一樣好。 – zx485

1

這應該工作:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    exclude-result-prefixes="xs" 
    version="2.0"> 

    <!-- 
     Convert first-level <topicref> elements to <appendix> and copy the attributes, 
     but ignore the @outputclass attribute 
    --> 
    <xsl:template match="topicref[contains(@outputclass, 'Dx:Appendix')][not(parent::topicref)]"> 
     <appendix> 
      <xsl:apply-templates select="@*[name()!='outputclass'] | node()"/> 
     </appendix> 
    </xsl:template> 

    <!-- 
     Copy all elements and attributes, except the @outputclass attribute 
     (default copy template) 
    --> 
    <xsl:template match="@* | node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*[name()!='outputclass'] | node()"/> 
     </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet>