How to re order the tags in one XML file based on another XML file in java using dom parser

26 Views Asked by At

I have one XML file say source.xml

<students>

  <student2>

    <college>SIET</college>

    <name>Rithvik</name>

  </student2>   

  <student1>

    <college>SCET</college>

    <name>Prabhas</name>

  </student1>

</students>

Also have referenced XML file say referenced.xml

<students>

  <student1>

    <name>Prabhas</name>

    <college>SCET</college>

  </student1>

  <student2>

     <name>Ritvik</name>

     <college>SIET</college>

  </student2>   

</students>

My requirement is to re order the tags of source XML file based on referenced XML file. Finally the source XML to become like referenced XML.

Output: source.xml

<students>

  <student1>

    <name>Prabhas</name>

    <college>SCET</college>

  </student1>

  <student2>

     <name>Ritvik</name>

     <college>SIET</college>

  </student2>  
 
</students>

I have tried in many ways but can't find the solution for it. It would be a great favour if you helped me

1

There are 1 best solutions below

0
Michael Kay On

I can't see any conceivable reason for wanting to do this with DOM rather than with XSLT.

In XSLT (2.0 or 3.0):

(a) Get a list of the element names in the order they appear in the reference document, for example

<xsl:variable name="elNames" 
     select="doc('reference.xml')//person[1]/*/local-name()"/>

(b) sort the children of a person element in your input document according to this list:

<xsl:template match="person">
  <person>
    <xsl:perform-sort select="*">
      <xsl:sort select="index-of($elNames, local-name())"/>
    </xsl:perform-sort>
  </person>
</xsl:template>