2009-05-18 91 views
3

我有一些XML包含記錄和子記錄,就像這樣:移動子節點爲母公司與XSLT屬性

<data> 
    <record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00"> 
     <record jsxid="id0x0b60ff10" string="101"/> 
     <record jsxid="id0x0e64d8e8" string="63"/> 
     <record jsxid="id0x2fd83f08" string="Y"/> 
    </record> 
    <record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00"> 
     <record jsxid="id0x0b60ff10" string="102"/> 
     <record jsxid="id0x0e64d8e8" string="77"/> 
     <record jsxid="id0x2fd83f08" string="Y"/> 
    </record>  
<data> 

我需要改變它,這樣的子記錄的字符串屬性被帶到成父記錄的連續編號的屬性,然後丟棄,像這樣:

<data> 
    <record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00" 1="101" 2="63" 3="Y"/> 
    <record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00" 1="102" 2="77" 3="Y"/> 
<data> 

的子記錄數是跨文檔任意的,但仍然是相同的文件中靜態的。

有人會如此友善地指向XSLT解決方案嗎?非常感謝。

回答

5

下面是一個完整的解決方案:

<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <!-- By default, recursively copy all nodes unchanged --> 
    <xsl:template match="@* | node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
    </xsl:template> 

    <!-- But don't process any children of <record> (such as whitespace)... --> 
    <xsl:template match="record/node()"/> 

    <!-- ...except for doubly-nested records; 
     convert them to attributes, named according to position --> 
    <xsl:template match="record/record" priority="1"> 
    <xsl:variable name="pos"> 
     <xsl:number/> 
    </xsl:variable> 
    <xsl:attribute name="r{$pos}"> 
     <xsl:value-of select="@string"/> 
    </xsl:attribute> 
    </xsl:template> 

</xsl:stylesheet> 

請注意,我改變了你的屬性,以「R1」,「R2」等的名字,因爲XML不允許你用一個開始的名字數。

1

這可能做到這一點,處理頂層<record>元素時運行此以下XSLT的片段:

<xsl:for-each select="record"> 
    <xsl:attribute name="{position()}"> 
     <xsl:value-of select="@string" /> 
    </xsl:attribute> 
</xsl:for-each> 

本質上這遍歷每個子<record>元件,並創建一個<xsl:attribute>元件描述所需屬性。調用position()函數以獲取頂級元素內的相對位置:1,2,3等。

這不是一個完整的解決方案;假定對XSLT有一定的瞭解。

+0

哈哈,在你的危險:-) – mysomic 2009-05-18 01:37:14

+0

....雖然這是絕對在我的雷達,訂單現在在亞馬遜。 – mysomic 2009-05-18 01:38:03