- String str1 = n1.getKey().getLocalName();
- if (n1 instanceof SimpleNode)
- str1 += ((SimpleNode<?>) n1).getValue();
-
- String str2 = n2.getKey().getLocalName();
- if (n2 instanceof SimpleNode)
- str2 += ((SimpleNode<?>) n2).getValue();
-
- return str1.compareTo(str2);
+ if (n1 instanceof SimpleNode && n2 instanceof SimpleNode) {
+ // if they're SimpleNodes just compare their strings
+ String str1 = n1.getKey().getLocalName() + ((SimpleNode<?>)n1).getValue();
+ String str2 = n2.getKey().getLocalName() + ((SimpleNode<?>)n2).getValue();
+ return str1.compareTo(str2);
+ } else if (n1 instanceof CompositeNode && n2 instanceof CompositeNode) {
+ // if they're CompositeNodes, things are more interesting
+ String str1 = n1.getKey().getLocalName();
+ String str2 = n2.getKey().getLocalName();
+ if (!str1.equals(str2)) {
+ // if their local names differ, return that difference
+ return str1.compareTo(str2);
+ } else {
+ // otherwise, we need to look at their contents
+ ArrayList<Node<?>> l1 = new ArrayList<Node<?>>( ((CompositeNode)n1).getValue() );
+ ArrayList<Node<?>> l2 = new ArrayList<Node<?>>( ((CompositeNode)n2).getValue() );
+
+ if (l1.size() != l2.size()) {
+ // if they have different numbers of things in them return that
+ return l2.size() - l1.size();
+ } else {
+ // otherwise, compare the individual elements, first sort them
+ Collections.sort(l1, this);
+ Collections.sort(l2, this);
+
+ // then compare them individually
+ for(int i = 0 ; i < l2.size() ; i++) {
+ int diff = this.compare(l1.get(i), l2.get(i));
+ if(diff != 0){
+ return diff;
+ }
+ }
+ return 0;
+ }
+ }
+ } else if (n1 instanceof CompositeNode && n2 instanceof SimpleNode) {
+ return -1;
+ } else if (n2 instanceof CompositeNode && n1 instanceof SimpleNode) {
+ return 1;
+ } else {
+ assertTrue("Expected either SimpleNodes CompositeNodes", false);
+ return 0;
+ }