Wednesday, 12 October 2016

XML : Java : Exception in thread "main" java.lang.NullPointerException at java.util.TimSort.countRunAndMakeAscending(TimSort.java:351) [duplicate]

This question already has an answer here:

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 creating a XML file from the XML String and trying to use comparator based on attribute key but am getting NUll Pointer on Comparator Object. 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());  }    

Am getting Null pointer at this line

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.

No comments:

Post a Comment