Lajos Zadravecz
Lajos Zadravecz

Reputation: 103

How to delete an element from an xml file in Java

 <?xml version="1.0" encoding="UTF-8" standalone="no"?><PetStore xmlns="http://www.training.mo.gov/PetStore">

      <Pet>
        <ID_Number>2</ID_Number>
        <Name>Max</Name>
        <Type>Dog</Type>
        <Age>13</Age>
      </Pet>
        <Pet>
        <ID_Number>5</ID_Number>
        <Name>Denzel</Name>
        <Type>Rat</Type>
        <Age>54</Age>
      </Pet>
      <Pet>
        <ID_Number>7</ID_Number>
        <Name>Pooch</Name>
        <Type>Snake</Type>
        <Age>5</Age>
      </Pet>
    </PetStore>

here is my xml code

public void removePet(int petId) throws IllegalArgumentException {
    NodeList pets = xmlDoc.getElementsByTagName("Pet"); // List of the Pet node's child nodes

    int numPets = pets.getLength();
    for (int i = 0; i < numPets; i++) {
        Node nNode = pets.item(i);
        Element petElement = (Element) nNode;
        if (petId == Integer.parseInt(petElement.getElementsByTagName("ID_Number").item(0).getTextContent())){
            nNode.getParentNode().removeChild(nNode);
            //break;    
        }
    }

    try {
        transform(xmlDoc);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

then my java function for removing the Pet element however a null pointer exception gets thrown on my if statement and the node isn't removed. not sure as to what needs to be done to correctly remove the element from this point. the break fixes this problem temporarily but then in another function to remove all the Pet elements this break on allows to remove one element. I know that is due to the break. now trying to figure out how to accomplish both removes without the break

Upvotes: 0

Views: 2735

Answers (1)

Josh H
Josh H

Reputation: 274

Deleting a node in a NodeList will cause the NodeList to be updated. At that point the last node you are trying to reach does not exist at the index you are expecting. Try keeping a set of targets to be updated, then remove them:

    Set<Element> targetElements = new HashSet<Element>();

    int numPets = pets.getLength();
    for (int i = 0; i < numPets; i++) {
        Node nNode = pets.item(i);
        Element petElement = (Element) nNode;
        if (5 == Integer.parseInt(petElement.getElementsByTagName("ID_Number").item(0).getTextContent())){
            targetElements.add(petElement);
        }
    }

    for (Element e: targetElements) {
      e.getParentNode().removeChild(e);
    }

You will also need apply this technique in your method that delete all pet elements.

See: Removing DOM nodes when traversing a NodeList

Upvotes: 1

Related Questions