How to reverse XML data tags using XSLT?

前提是你 提交于 2019-12-12 06:06:31

问题


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>2</id>

Any Idea folks ?


回答1:


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




回答2:


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.




回答3:


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() &lt; 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() &gt; 1]"/>
</xsl:template>


来源:https://stackoverflow.com/questions/5572501/how-to-reverse-xml-data-tags-using-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!