DOM4J对节点元素进行数字排序

huangapple go评论81阅读模式
英文:

DOM4J sorting node elements numerically

问题

我正在使用DocumentHelper来对节点列表进行排序,类似下面的代码,但看起来它是按字母数字顺序排序的。XPath指向一个基于整数的属性。我该如何修改这段代码以进行基于整数的排序?

private void sortNodesByIndex(Element parent, List<Node> pointList) {
    DocumentHelper.sort(pointList, new Comparator<Node>() {
        @Override
        public int compare(Node node1, Node node2) {
            int index1 = Integer.parseInt(node1.valueOf("@Index"));
            int index2 = Integer.parseInt(node2.valueOf("@Index"));
            return Integer.compare(index1, index2);
        }
    });
    for (Node node : pointList) {
        parent.remove(node);
        parent.add(node);
    }
}

这段修改后的代码将使用一个自定义的比较器来进行基于整数的排序。比较器将解析节点的"@Index"属性值,并将其转换为整数进行比较。然后,根据比较结果进行排序。

英文:

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&lt;Node&gt; pointList) {
        DocumentHelper.sort(pointList, &quot;@Index&quot;);
        for (Node node : pointList) {
            parent.remove(node);
            parent.add(node);
        }
    }

答案1

得分: 0

经过一番折腾后,我决定使用自定义的比较器。这可能不是最好的解决方案,但它能够工作!

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);
    }
}
英文:

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&lt;Node&gt; {
        public int compare(Node a1, Node b1) {
            Element a2 = (Element) a1;
            Element b2 = (Element) b1;
            Integer a = Integer.parseInt(a2.attributeValue(&quot;Index&quot;));
            Integer b = Integer.parseInt(b2.attributeValue(&quot;Index&quot;));
            return a.compareTo(b);
        }
    }

huangapple
  • 本文由 发表于 2023年8月9日 10:32:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864216.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定