开发者

Reversing XML data tags using XSLT ?

For example, in the below XML file:

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

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

    <name>Chris</name>
    <id>3开发者_JAVA百科</id>
</person>

In XSLT I code:

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

So that in the HTML file It renders

John1Diane2Chris3

.

But, I need following output: Diane2John1Chris3

I need to reverse order of first 2 data tags. Here below first 2 tags

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

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

Any Idea folks ?


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

Erm, sorry, this is for reversing them completely, I can see you don't really want to reverse everything.

In that case the easiest way is to just hand-code the order in the ` select attribute:

<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>

(By the way, this isn't a very good format to store your data, you should wrap each person in a <person> tag, as just writing them one after the other and then fiddling with the order is an accident waiting to happen.)


If you always just need to swap the first 2 people then you can do this:

<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>

This would be easier if you had separate <person> elements for each "name" & "id" pair.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜