KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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: <?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 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. 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().removeChi
Tags (comma-separated)
Save Edits
Cancel