[XOM-interest] How to sort elements...?

Adam Constabaris adamc at unc.edu
Mon May 5 09:07:12 EDT 2008


I'd like to suggest using XSLT for this job; it's less brittle and 
easier to customize than using the XOM API directly.  You could use an 
identity stylesheet (e.g. 
http://www.dpawson.co.uk/xsl/sect2/identity.html) and add the following 
template to accomplish the task:

<xsl:template match="a">
  <xsl:for-each select="b">
   <xsl:sort select="@key"/>
   <xsl:apply-templates select="."/>
  </xsl:for-each>
</xsl:template>

------------------

This works nicely even if you created the document you're trying to 
transform in XOM, because the XSLT support is right there.

If you really want or need to do this completely via the XOM API, then 
the most straightforward approach would is the one you're probably 
looking for an alternative to: copy the elements of interest into a 
java.util.List, detach/remove those elements from the parent, sort the 
list with a java.lang.Comparator implementation, and add them back in 
sorted order.

[ As a coding shortcut for most of the first two steps, note that 
Element.removeChildren() returns the removed Nodes object ]

HTH,

AC

Manfred Lotz wrote:
> Hi all,
> I want to modify an xml document by sorting the children of a specific 
> element.
> 
> Assuming I have something like this:
> 
> <a>
>   <b key="xyz"> .... </b>
>   <b key="sssssyz"> .... </b>
>   <b key="eyz"> .... </b>
>   <b key="qyz"> .... </b>
>   <b key="abc"> .... </b>
> </a>
> 
> I want to sort the <b> elements according to the key value and write the 
> modified xml document to a file.
> 
> 
> I can put the <b> elements in Elements
> 	Elements bElements = doc.getRootElement().getChildElements();
> 
> but this gives me iteration only.
> 
> 
> How can I do it?



More information about the XOM-interest mailing list