title: Java Sort Xml by element
body: <p>I am trying to sort this XMl </p>
  
  <pre><code>&lt;phoneBook first="JJ"&gt;
      &lt;last&gt;Jo&lt;/last&gt;
      &lt;type&gt;Cellphone&lt;/type&gt;
  &lt;/phoneBook&gt;
  </code></pre>
  
  <p>by the element last.</p>
  
  <pre><code>public static Map&lt;String, Node&gt; sortElements(Document doc, Map&lt;String, Node&gt; map, String sortBy){
          if(map == null)
              map = new HashMap&lt;&gt;();
          NodeList selection =doc.getElementsByTagName("phoneBook");      
          for(int i = 0; i &lt; selection.getLength(); i++){
              Node rel = selection.item(i);
              for(int j = 0; j &lt; rel.getChildNodes().getLength(); j++){
                  Node jn = rel.getChildNodes().item(j);
                  if(jn.getNodeName().equals(sortBy)){
                      map.put(jn.getNodeValue(), rel);
                  }}}
          return new TreeMap&lt;&gt;(map);
      }
  </code></pre>
  
  <p>unfortunately one node is empty.It throws NPE!
  I call the method like this inside DOM Parser!</p>
  
  <pre><code>SortPhoneBook.sortElements(doc, null, "last");
  </code></pre>
  
  <p>Can anybody help me?</p>