Java Mailing List Archive

http://www.junlu.com/

Home » JDOM Projects »

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

msook

2008-03-01

Replies: Find Java Web Hosting

Author LoginPost Reply

Hello,
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
<resources>
<resource type="webcontent" identifier="acb-123"
href="aaa/bbb263.xhtml">
<file href="aaa/bbb263.xhtml" />
</resource>
<resource type="webcontent" identifier="sbs-345"
href="aaa/ccc264.xhtml">
<file href="aaa/ccc264.xhtml" />
</resource>
<resource type="quiz" identifier="ccc-222"
href="aaa/bbb159.xml">
<file href="aaa/ccc159.xml" />
</resource>
<resource type="quiz" identifier="ddd-123"
href="aaa/ddd170.xml">
<file href="aaa/ddd170.xml" />
</resource>
</resources>

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
being
// added twice.
while(contentIter.hasNext())
{
Object obj = contentIter.next();
if (obj instanceof Element)
contentIter.set(childrenIter.next());
}

// Finally, we set the content list back into the parent Element.
parent.setContent(null);
parent.setContent(content);
}

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

Thanks in advance.

--
Sent from the JDOM - General mailing list archive at Nabble.com.

_______________________________________________
To control your jdom-interest membership:
http://www.jdom.org/mailman/options/jdom-interest/youraddr@(protected)
©2008 junlu.com - Jax Systems, LLC, U.S.A.