1

I have a String formatted as XML and trying to sort it. I thought of creating an XML file from String and then sort the xml file itself.

I am using JDOM library to try to sort the XML. I have created a JDOM document from the string and am trying to use comparator based on attribute as key but am getting NullPointerException on comparing. Below is the code:

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());
}

This line throws the exception:

return o2.getAttributeValue(key).compareTo(o1.getAttributeValue(key));

Here is the 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)

Am not able to understand whats wrong. Please help.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
roger_that
  • 9,493
  • 18
  • 66
  • 102

0 Answers0