save xml object so that elements are in sorted order in saved xml file
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.
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.
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.
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.
精彩评论