2014-03-30 136 views
1

所以,我有我從具有這種基本結構,政府下載了一些XML數據:轉換XML元素與屬性爲所有屬性

<axis pos="6" values="3"> 
    <title>Device</title> 
    <label code="7">Autologous Tissue Substitute</label> 
    <label code="J">Synthetic Substitute</label> 
    <label code="K">Nonautologous Tissue Substitute</label> 
</axis> 

而且我想用XSLT來獲得輸出看起來是這樣的(我將然後加載到關係型數據庫表):

<axis pos="6" title="Device" code="7" label="Autologous Tissue Substitute" /> 
<axis pos="6" title="Device" code="J" label="Synthetic Substitute" /> 
<axis pos="6" title="Device" code="K" label="Nonautologous Tissue Substitute" /> 

我真的不知道XSLT非常好(即我剛剛看了網上的一些教程了大約一個小時。)所以我想到的是:

<xsl:template match="axis"> 
    <axis pos="{pos}"> 
     <xsl:for-each select="*"> 
     <xsl:attribute name="{name()}"> 
      <xsl:value-of select="text()" /> 
     </xsl:attribute> 
     </xsl:for-each> 
    </axis> 
</xsl:template> 

這導致:

<axis pos="" title="Device" label="Nonautologous Tissue Substitute"/> 

的第一個問題是空值的POS屬性和遺漏碼屬性。但更大的問題是我只能得到一個軸標籤而不是三個。我感覺我要麼在錯誤的標籤級別上工作,要麼我錯過了每一個。

任何幫助/鏈接到有用的教程表示讚賞。

回答

0

首先,因爲您想爲每個子節點label節點輸出一個axis節點輸出,所以需要迭代後者。從那裏你可以參考父母的信息,生活在該級別。

此外,符合apply-templates,這通常是優於在for-each之上的XSLT。

<!-- kick things off --> 
<xsl:template match="axis"> 
    <xsl:apply-templates select='label' /> 
</xsl:template> 

<!-- do axis node, one per label child in source XML --> 
<xsl:template match='label'> 
    <axis pos='{../@pos}' title='{../title}' code='{@code}' label='{.}' /> 
</xsl:template> 

注意,因爲屬性通過前綴@引用您的pos屬性是空的;省略它會告訴XSLT處理器查找子節點,而不是屬性。在this XMLPlayground

可運行演示(見輸出

+0

這是很好的。有沒有辦法做到這一點,而不必指定軸和標籤的屬性,但動態地完成它(如果格式改變)? – JoeNahmias