views:

56

answers:

3

Hi ,

I am saving a xml document object and it is saved in a xml file as shown below .

<author name="tom" book="Fun-II"/>
<author name="jack" book="Live-I"/>
<author name="pete" book="Code-I"/>
<author name="jack" book="Live-II"/>
<author name="pete" book="Code-II"/>
<author name="tom" book="Fun-I"/>

instead i want to sort the content in document object so that when i persist the object it is saved by grouping authors then book name as below:

<author name="jack" book="Live-I"/>
<author name="jack" book="Live-II"/>
<author name="pete" book="Code-I"/>
<author name="pete" book="Code-II"/>
<author name="tom" book="Fun-I"/>
<author name="tom" book="Fun-II"/>

I use apache xml beans..any ideas on how to achieve this?

thanks.

+3  A: 

XML has no sorting order, you could transform XML by using XSLT Something like that:

<xsl:for-each select="author" order-by="+ name">
<tr>
    <td><xsl:value-of select="@name"/></td>
    <td><xsl:value-of select="@book"/></td>
</tr>
</xsl:for-each>

See also Sorting in XSLT for furhter ideas.

stacker
A: 

As stacker already mentioned, plain xml documents are never (usually?) not sorted or sortable. To have sorted xml documents, you could either sort the model before serializing it or create/use an external sorter to process existing xml documents.

Andreas_D
A: 

It should also be noted that the element

<author name="pete" book="Code-I"/>

Is identical to:

<author book="Code-I" name="pete"/>

Attribute nodes, unlike text nodes and element nodes have no ordering. Thus for the purposes of XML, you have to tell it on which attribute it should sort.

Lajla