Skip to Content

Reorder the XML node from last to first

HiExperts,

I have below xml structure

<head><item><f1>a</f1><f2>b</f2></item><item><f1>c</f1><f2>d</f2></item></head>

I want the "item" nodes to be reversed,i.e.,from last to first.Please help me with the relevant for the same.

ThankYou.

Ahmed

Add comment
10|10000 characters needed characters exceeded

  • Get RSS Feed

3 Answers

  • Oct 26, 2017 at 10:45 AM

    Hi Ahmed!

    This can be easily done using XSL transformation:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:template match="/">
            <head>
                <xsl:apply-templates select="/head/item">
                    <xsl:sort select="position()" data-type="number" order="descending"/>
                </xsl:apply-templates>
            </head>
        </xsl:template>
        <xsl:template match="item">
            <xsl:copy-of select="."/>
        </xsl:template>
    </xsl:stylesheet>

    Result (according to your test data provided above):

    <?xml version="1.0" encoding="utf-8"?>
    <head>
        <item>
            <f1>c</f1>
            <f2>d</f2>
        </item>
        <item>
            <f1>a</f1>
            <f2>b</f2>
        </item>
    </head>

    Regards, Evgeniy.

    Add comment
    10|10000 characters needed characters exceeded

  • Oct 26, 2017 at 08:12 AM

    Hi Ahmed,

    The use of index (Do Not Reset to Initial Values) and sortByKey (descending) should solve your issue.

    F1

    F2

    Test

    Regards,

    Mark

    Add comment
    10|10000 characters needed characters exceeded

  • Oct 26, 2017 at 08:27 AM

    Hello Farooq,

    If my understanding is not wrong you just to wish to reverse ITEMS Note.Try the below approach

    UDF(All Values of Queue):

    for(int i=var1.length-1;i>=0;i--)
    {
    result.addValue(var1[i]);
    }

    Map it to F1 and F2 Nodes

    Sample Input and Output:

    If this is not the requirement please post the sample input and output XMLs.

    Add comment
    10|10000 characters needed characters exceeded