简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM