[jdom-interest] How can I sort elements by an attribute value?

msook lmsook10 at hotmail.com
Sat Mar 1 06:20:47 PST 2008

I'm pretty new in JDOM world, and I've got very excited project that I am
really interested in.
The xml file looks like
<resource type="webcontent" identifier="acb-123"
<file href="aaa/bbb263.xhtml" />
<resource type="webcontent" identifier="sbs-345"
<file href="aaa/ccc264.xhtml" />
<resource type="quiz" identifier="ccc-222"
<file href="aaa/ccc159.xml" />
<resource type="quiz" identifier="ddd-123"
<file href="aaa/ddd170.xml" />

And as you guess, there is a node called "resources" and under that node,
each resource's attribute href value is added(showing).
But I need to fix it to show that under "resources" node(parent), each
resouce should be shown by href's alphabetical order.

I've read the codes example regarding "Sorting elements in a document
by a Node" and this is it.

public static void sortElements(Element parent, Comparator c) {
// Create a new, static list of child elements, and sort it.
List children = new ArrayList(parent.getChildren());
Collections.sort(children, c);
ListIterator childrenIter = children.listIterator();

// Create a new, static list of all content items.
List content = new ArrayList(parent.getContent());
ListIterator contentIter = content.listIterator();

// Loop through the content items, and whenever we find an Element,
// we'll insert the next ordered Element in its place. Because the
// content list is not live, it won't complain about an Element
// added twice.
Object obj = contentIter.next();
if (obj instanceof Element)

// Finally, we set the content list back into the parent Element.

But how can I sort elements by attribute?
Please share the code example if you have.

Thanks in advance.

View this message in context: http://www.nabble.com/How-can-I-sort-elements-by-an-attribute-value--tp15773258p15773258.html
Sent from the JDOM - General mailing list archive at Nabble.com.

More information about the jdom-interest mailing list