I have a very simple xml file that I would like to create a simple function to remove an element from it. Here is my xml file:
<?xml version="1.0"?>
<book>
<person>
<name>Person 1</name>
</person>
<person>
<name>Person 2</name>
</person>
<person>
<name>Person 3</name>
</person>
<person>
<name>Person 4</name>
</person>
</book>
I just want to call a method to remove a single name from a file. I am not very familiar with XML, but I was able to create a reader and writer, but now I am unable to create a method to remove an element from my file.
When I say delete an item, I mean:
deleteItem("Person 3");
And then the XML file will change to:
<?xml version="1.0"?>
<book>
<person>
<name>Person 1</name>
</person>
<person>
<name>Person 2</name>
</person>
<person>
<name>Person 4</name>
</person>
</book>
What did I do wrong:
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 < 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);
}
}
}
source
share