2013-06-28 119 views
0

我有以下XML源:如何用xslt更改簡單的xml層次結構?

<to id="abc"> 
    <ti></ti> 
    <b> 
    ... 
     <to id="bcd"><ti></ti><b>...</b></to> 
     <to id="cde"><ti></ti><b>...</b></to> 
     <to id="def"><ti></ti><b>...</b></to> 
    </b> 
</to> 

的 「...」 意味着很多bodydiv Li和nodetext之間的。

我想將它轉換爲:

<to id="abc"> 
    <ti></ti> 
    <b> 
    ... 
    </b> 
    <to id="bcd"><ti></ti><b>...</b></to> 
    <to id="cde"><ti></ti><b>...</b></to> 
    <to id="def"><ti></ti><b>...</b></to> 
</to> 

什麼是最簡單的方法來表達XSLT轉換?

回答

0

看來,你只在b之外移動to。不知道爲什麼你需要基於@id

試試這個:

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

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

    <xsl:template match="b"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()[not(self::to)]"/> 
     </xsl:copy> 
     <xsl:apply-templates select="to"/> 
    </xsl:template> 

</xsl:stylesheet> 
0

下應該做的,它使用的身份轉換模板複製一切,並增加了兩個模板,首先要處理to[@id = 'abc']元件和第二處理其b子元素:

<xsl:output indent="yes"/> 
<xsl:strip-space elements="*"/> 

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

<xsl:template match="to[@id = 'abc']"> 
    <xsl:copy> 
    <xsl:apply-templates select="@* | node() | b/to[@id]"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="to[@id = 'abc']/b"> 
    <xsl:copy> 
    <xsl:apply-templates select="@* | node()[not(self::to[@id])]"/> 
    </xsl:copy> 
</xsl:template> 
+0

非常感謝您對這個acurate的,快速的答案。現在我明白了更多這種XSLT'ing。我把[@id ='abc']「改成了」[@id =/to/@ id]「,所以我也得到了正確的結果,如果從頂級」to「元素的id等於自動生成的。 – CodeFreezr