title: How to get XML node by ID and NamedNodeMap - Java DOM XML
body: <p>I have an xml file with messages:</p>
  
  <pre><code>&lt;bus&gt;
      &lt;message id="58afdb36-9080-4dd8-922e-ee516b2b5073"&gt;
      &lt;retrievedDate&gt;Mon Feb 18 14:43:23 GMT 2013&lt;/retrievedDate&gt;
      &lt;addedDate&gt;Mon Feb 18 14:43:23 GMT 2013&lt;/addedDate&gt;
      &lt;state&gt;initialised&lt;/state&gt;
      &lt;content&gt;content placeholder&lt;/content&gt;
      &lt;/message&gt;
  &lt;/bus&gt;
  </code></pre>
  
  <p>I am creating a method to change the state of a message for a given ID.</p>
  
  <p>However I keep getting NullPointerException when I try to get the node with the ID I want. Have tried experimenting with <strong><em>getElementById</em></strong> and <strong><em>getElementsByTagName</em></strong>, but I always get null instead of the node I want.</p>
  
  <pre><code>public static int updateMessageState(UUID messageID, String newState) 
          throws ParserConfigurationException, 
                  SAXException, IOException, TransformerException {
  
      String filepath = "data.xml";
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(filepath);
  
      // Get Message
      Node message = doc.getElementById(messageID.toString());
  
      // Find and update the state
      NamedNodeMap atrMap = message.getAttributes();
      Node nodeAtr = atrMap.getNamedItem("state");
      nodeAtr.setTextContent(newState);
  
      // Save write to XML
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(new File(filepath));
      transformer.transform(source, result);
  
      return 0;
  }
  </code></pre>