2010-09-19 75 views
0

我可以使用XSL或類似的另一件事來改變這種格式變化xml格式的XSL或其他

<rr n="Address"> 
    <tt> 
    <j n="currentAddress">0</j> 
    <j n="city">city</j> 
    </tt> 
    </rr> 

這樣: -

<Address> 
    <tt> 
    <currentAddress>0</currentAddress> 
    <city>city</city> 
    </tt> 
    <Address> 

通知我想要的屬性值成爲元素並刪除屬性 如果可能請張貼方法。

謝謝

+3

是的。是的你可以。 – amphetamachine 2010-09-19 10:20:14

+0

可以請你發帖的方法 – new 2010-09-19 10:21:40

回答

1

該樣式也將工作:

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

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

<!--specialized template for elements with an "n" attribute--> 
<xsl:template match="*[@n]"> 
    <xsl:element name="{@n}"> 
     <xsl:apply-templates select="node()"/> 
    </xsl:element> 
</xsl:template> 

</xsl:stylesheet> 

identity template第一模板,該模板上匹配@*(這意味着任何屬性)和node()(這意味着任何元素,文本節點,處理指令或註釋)。默認行爲是複製匹配的項目,然後apply-templates到它的任何屬性或子節點。

如果在樣式表中沒有聲明其他模板,那麼該標識模板將匹配所有內容,並且XSLT將簡單地複製XML文檔。

第二個模板匹配*[@n],它是任何具有「n」屬性的元素。 *是任何元素的通配符匹配。方括號是謂詞過濾器,其行爲類似於SQL WHERE子句。謂詞中指定的任何條件都必須爲真,以便模板匹配選擇適合的任何條件。謂詞過濾器根據匹配項目的上下文進行評估,因此假設您「站立」在一個元素上,它是否具有@n?如果是這樣,那麼這個模板匹配。

第二個模板比第一個「標識」模板具有更具體的匹配標準,所以它會「勝出」並匹配具有@n的元素。

用於第二模板的邏輯是創建具有@n的值的名稱和元素那麼對於任意子node()apply-templates(它包括text()和元素,但不包括屬性)。

+0

非常感謝你的工作完美可以請你解釋一下我想了解答案 – new 2010-09-19 13:17:14

+0

我已經更新了答案和簡短的解釋。 – 2010-09-19 13:53:29

+0

+1有一個很好的解決方案和解釋。 – 2010-09-19 14:51:37

0

是的XSL可以使用:)。

這裏是XSL:

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


    <xsl:template match="/"> 
     <xsl:apply-templates /> 
    </xsl:template> 

    <xsl:template match="*"> 
     <xsl:choose> 
      <xsl:when test="@n"> 
       <xsl:variable name="eleName"> 
        <xsl:value-of select="@n" /> 
       </xsl:variable> 
       <xsl:element name="{$eleName}"> 
        <xsl:value-of select="text()" /> 
        <xsl:apply-templates select="*" /> 
       </xsl:element> 
      </xsl:when> 
      <xsl:otherwise> 
       <xsl:copy> 
        <xsl:apply-templates select="*" /> 
       </xsl:copy> 
      </xsl:otherwise> 
     </xsl:choose> 

    </xsl:template> 

</xsl:stylesheet>