2015-11-05 87 views
0

我的要求如下需要幫助的XSLT邏輯轉換的元素屬性爲元素

如果任何複雜的元素包含則對應元素的屬性轉換成元素的父級純文本。

如果任何複雜元素包含子元素,那麼相應的元素屬性會將元素轉換爲相同元素級別的元素。

此翻譯想要使用xslt邏輯實現。

輸入XML


<root> 
    <food name="desert">butter scotch</food> 
    <special type="nonveg"> 
     <name>chicken</name> 
    </special> 
</root> 

輸出XML


<root> 
<food>butter scotch</food> 
<name>desert</name> 
<special> 
    <type>nonveg</type> 
    <name>chicken</name> 
</special> 
</root> 

回答

1

開始了與身份變換....

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

對於規則「如果任何複雜元素只包含文本,則相應的元素屬性將轉換爲父級的元素」,則可以使用以下模板(我在此忽略註釋和處理指令,只檢查元素是否子元素)

<xsl:template match="*[not(*)][@*]"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()"/> 
    </xsl:copy> 
    <xsl:apply-templates select="@*" mode="toelement"/> 
</xsl:template> 

帶模式「toelement」的模板會將屬性轉換爲元素。 (它將被其他規則重新使用)。

<xsl:template match="@*" mode="toelement"> 
     <xsl:element name="{local-name()}"> 
      <xsl:value-of select="." /> 
     </xsl:element> 
    </xsl:template> 

對於規則「如果任何複雜的元素包含兒童則對應元素的屬性轉換成元素相同的元素水平。」那麼你實際上可以匹配直接屬性:

<xsl:template match="*[*]/@*"> 
    <xsl:apply-templates select="." mode="toelement"/> 
</xsl:template> 

嘗試此XSLT:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output method="xml" indent="yes" /> 

    <xsl:template match="*[*]/@*"> 
     <xsl:apply-templates select="." mode="toelement"/> 
    </xsl:template> 

    <xsl:template match="*[not(*)][@*]"> 
     <xsl:copy> 
      <xsl:apply-templates select="node()"/> 
     </xsl:copy> 
     <xsl:apply-templates select="@*" mode="toelement"/> 
    </xsl:template> 

    <xsl:template match="@*" mode="toelement"> 
     <xsl:element name="{local-name()}"> 
      <xsl:value-of select="." /> 
     </xsl:element> 
    </xsl:template> 

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

非常感謝Tim。但我有一個更多的要求,那就是每個屬性,而轉換爲元素需要追加它的元素名稱。例如下面輸入XML: ******************** butter scotch 輸出XML ********************* 黃油糖塊 沙漠 nonveg Bablu

+0

添,能否請您迴應?提前致謝。 – Bablu

+0

@NaveenPamulapati蒂姆的答案完美地處理了你的問題,輸出結果與你在問題中闡述的一樣,並且有一個很好的解釋。我建議你接受這個好的答案,如果你還有其他問題(在原問題的範圍之外),你應該問一個新的問題。當我離開電腦並回來時,我恰好坐在這個問題上。 但是,在選擇屬性'' –