How to reverse XML data tags using XSLT?
For example, below XML file.
<person>
<name>John</name>
<id>1</id>
<name>Diane</name>
<id>2</id>
<name>Chris</name>
<id>3</id>
</person>
Now, In XSLT, If I code:
<xsl:template match="person">
<xsl:apply-templates/>
</xsl:template>
So, In HTML file It will display 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>开发者_StackOverflow社区2</id>
Any Idea folks ?
<xsl:template match="person">
<xsl:apply-templates select="name[2]|id[2]"/>
<xsl:apply-templates select="name[position() != 2]|id[position() != 2]"/>
</xsl:template>
This assumes there is always a name
and id
pair. If that's not the case, solution will be more complex.
Here's a very specific solution to a very specific problem:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="person">
<xsl:apply-templates select="name[text()='Diane']|id[text()='2']" />
<xsl:apply-templates select="name[not(text()='Diane')] |
id[not(text()='2')]" />
</xsl:template>
</xsl:stylesheet>
Output:
Diane2John1Chris3
A more general solution would require a more general description of the problem.
The code below will allow you to control how much of first tags you want to reverse but I tend to agree with lwburk that it might be overkill if you know for sure that all you need is just to inverse only two first tags.
<xsl:template match="person">
<xsl:for-each select="name[position() < 3]">
<xsl:sort select="position()" data-type="number" order="descending"/>
<xsl:apply-templates select="."/>
<xsl:apply-templates select="./following-sibling::id[position() = 1]"/>
</xsl:for-each>
<xsl:apply-templates select="name[position() = 2]/following-sibling::*[position() > 1]"/>
</xsl:template>
精彩评论