我有一个格式化为XML的字符串并尝试对其进行排序。我想过从String创建一个XML文件,然后对xml文件本身进行排序。
我正在使用JDOM库来尝试对XML进行排序。我已经从字符串创建了一个JDOM文档,并尝试使用基于属性的比较器作为键,但在比较时得到NullPointerException。以下是代码:
File xmlFile = new File(filePath);
SAXBuilder builder = new SAXBuilder();
org.jdom2.Document document = null;
try {
document = (org.jdom2.Document) builder.build(xmlFile);
} catch (JDOMException e1) {
System.out.println(Constants.JDOM_ERROR+e1.getLocalizedMessage());
} catch (IOException e1) {
System.out.println(Constants.IO_EXCEPTION+e1.getMessage());
}
org.jdom2.Element rootElement = document.detachRootElement();
List<org.jdom2.Element> children = new ArrayList<org.jdom2.Element>(rootElement.getChildren());
rootElement.removeContent();
Comparator<org.jdom2.Element> comparator = new Comparator<org.jdom2.Element>() {
public int compare(org.jdom2.Element o1, org.jdom2.Element o2) {
return o2.getAttributeValue(key).compareTo(o1.getAttributeValue(key));
}
};
Collections.sort(children, comparator);
org.jdom2.Document newDocument = new org.jdom2.Document(rootElement);
rootElement.addContent(children);
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
try {
xmlOutput.output(newDocument, new FileWriter("sorted.xml"));
} catch (IOException e) {
System.out.println(Constants.IO_EXCEPTION+e.getMessage());
}
此行抛出异常:
return o2.getAttributeValue(key).compareTo(o1.getAttributeValue(key));
这是stacktrace:
Exception in thread "main" java.lang.NullPointerException
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:351)
at java.util.TimSort.sort(TimSort.java:230)
at java.util.Arrays.sort(Arrays.java:1512)
at java.util.ArrayList.sort(ArrayList.java:1454)
at java.util.Collections.sort(Collections.java:175)
我无法理解什么是错的。请帮忙。