title: java xml remove item
body: <p>I have a very simple xml file that I would like to create a simple function to remove an item from it. Here is my xml file:</p>
  
  <pre><code>    &lt;?xml version="1.0"?&gt;
  &lt;book&gt;
    &lt;person&gt;
      &lt;name&gt;Person 1&lt;/name&gt;
    &lt;/person&gt;
    &lt;person&gt;
      &lt;name&gt;Person 2&lt;/name&gt;
    &lt;/person&gt;
    &lt;person&gt;
      &lt;name&gt;Person 3&lt;/name&gt;
    &lt;/person&gt;
    &lt;person&gt;
      &lt;name&gt;Person 4&lt;/name&gt;
    &lt;/person&gt;
  &lt;/book&gt;
  </code></pre>
  
  <p>I simply want to call a method to delete one name from the file. I'm not very familiar with XML but did manage to create a reader and writer but now I'm having trouble creating a method to delete an item from my file.</p>
  
  <p>When I say delete an item I mean:</p>
  
  <pre><code>deleteItem("Person 3");
  </code></pre>
  
  <p>And then the XML file will change to:</p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
      &lt;book&gt;
        &lt;person&gt;
          &lt;name&gt;Person 1&lt;/name&gt;
        &lt;/person&gt;
        &lt;person&gt;
          &lt;name&gt;Person 2&lt;/name&gt;
        &lt;/person&gt;
        &lt;person&gt;
          &lt;name&gt;Person 4&lt;/name&gt;
        &lt;/person&gt;
      &lt;/book&gt;
  </code></pre>
  
  <p>What did I do wrong:</p>
  
  <pre><code>public static void removeName(String personName) throws ParserConfigurationException, IOException, SAXException{
          DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
          DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
          Document doc = docBuilder.parse (new File("test.xml"));
  
          NodeList nodes = doc.getElementsByTagName("person");
          for (int i = 0; i &lt; nodes.getLength(); i++) {       
              Element person = (Element)nodes.item(i);
              Element name = (Element)person.getElementsByTagName("name").item(0);
              String pName = name.getTextContent();
              if(pName.equals(personName)){
                  person.getParentNode().removeChild(person);
              }
          }
  
      }
  </code></pre>