英文:
DOM4J sorting node elements numerically
问题
我正在使用DocumentHelper来对节点列表进行排序,使用类似下面的代码,但看起来它是按字母数字顺序排序的。XPath指向一个基于整数的属性。如何调整这段代码以进行基于整数的排序?
private void sortNodesByIndex(Element parent, List<Node> pointList) {
DocumentHelper.sort(pointList, "@Index", new NumberComparator());
for (Node node : pointList) {
parent.remove(node);
parent.add(node);
}
}
class NumberComparator implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Node && o2 instanceof Node) {
Node node1 = (Node) o1;
Node node2 = (Node) o2;
// Get the integer values from the nodes' attributes
int index1 = Integer.parseInt(node1.valueOf("@Index"));
int index2 = Integer.parseInt(node2.valueOf("@Index"));
// Compare the integer values
return Integer.compare(index1, index2);
}
return 0;
}
}
请将上述代码添加到您的项目中,并确保导入了相关的类和包。这将使用NumberComparator
来执行基于整数的排序。
英文:
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);
}
}
答案1
得分: 0
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);
}
}
英文:
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论