2011-04-06 107 views
1

例如,下面的XML文件中:使用XSLT顛倒XML數據標籤?

<person> 
    <name>John</name> 
    <id>1</id> 

    <name>Diane</name> 
    <id>2</id> 

    <name>Chris</name> 
    <id>3</id> 
</person> 

在XSLT我的代碼:

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

所以,在HTML文件,它使得

John1Diane2Chris3

但是, 我需要下面的輸出: Diane2John1Chris3

我需要扭轉第一2個數據標記的順序。 以下是前2個標籤

<name>John</name> 
<id>1</id> 

<name>Diane</name> 
<id>2</id> 

任何創意人?

+1

這是http://stackoverflow.com/questions/5572501/的重複how-to-reverse-xml-data-tags-using-xslt - 請參閱我的答案 – 2011-04-06 21:18:23

回答

0

如果你總是隻需要交換第2人,那麼你可以這樣做:

<xsl:template match="person"> 
<xsl:apply-templates select="name[position()=2]" /> 
<xsl:apply-templates select="id[position()=2]" /> 

<xsl:apply-templates select="name[position()=1]" /> 
<xsl:apply-templates select="id[position()=1]" /> 

<xsl:apply-templates select="node()[position() &gt; 4]" /> 
</xsl:template> 

如果你有每個「名」 &「ID」對獨立<person>元素這會更容易些。

1
<xsl:template match="person"> 
    <xsl:apply-templates select="reverse(*)"/> 
</xsl:template> 

呃,對不起,這是爲了完全扭轉它們,我可以看到你並不是真的想要扭轉一切。

在這種情況下,最簡單的方法是隻手代碼在'選擇屬性的順序:

<xsl:template match="person"> 
    <xsl:apply-templates select="name[2]"/> 
    <xsl:apply-templates select="id[2]"/> 
    <xsl:apply-templates select="name[1]"/> 
    <xsl:apply-templates select="id[1]"/> 
    ... 
</xsl:template> 

(順便說一下,這是不是一個很好的格式來存儲你的數據,你應該將每個人包裝在一個<person>標籤中,因爲只是一個接一個地寫入它們,然後擺弄訂單是一個等待發生的事故。)