Paul Kennedy
Paul Kennedy

Reputation: 45

DOM4J sorting node elements numerically

I am using DocumentHelper to sort a node list using code similar to below, but it looks like it is sorting alphanumerically. The xPath points to an Integer based attribute. How do I adapt this code to do an Integer based sort?

private void sortNodesByIndex(Element parent, List<Node> pointList) {
        DocumentHelper.sort(pointList, "@Index");
        for (Node node : pointList) {
            parent.remove(node);
            parent.add(node);
        }
    }

Upvotes: -1

Views: 71

Answers (1)

Paul Kennedy
Paul Kennedy

Reputation: 45

After a lot of messing around I decided to use a custom Comparator. It may not be the best solution but it works!

if (!nodeList.isEmpty()) {
                Collections.sort(nodeList, new SortByIndexComparator());
                Element parent = nodeList.get(0).getParent();
                for (Node node : nodeList) {
                    parent.remove(node);
                    parent.add(node);
                }
            }
class SortByIndexComparator implements Comparator<Node> {
        public int compare(Node a1, Node b1) {
            Element a2 = (Element) a1;
            Element b2 = (Element) b1;
            Integer a = Integer.parseInt(a2.attributeValue("Index"));
            Integer b = Integer.parseInt(b2.attributeValue("Index"));
            return a.compareTo(b);
        }
    }

Upvotes: 0

Related Questions