Alex Rivera | Logout

java xml remove item

Asked 2011-08-11T16:22:53.610
9

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
Edit
Report

1 Answer

2

first select the item with the good text.

To do that, use xpath syntax : /book/person[name/text() = "Person 3"]

After that, you will have the node, simply remove it from its parent.

Here is the code (not tested) :

InputSource source = new InputSource(new FileInputStream(##your file##));

XPathFactory builder = XPathFactory.newInstance();
XPath xpath = builder.newXPath();

String label = "Person 3";
XPathExpression exp = xpath.compile("/book/person[name/text() = \"" + label +"\"]");

Node node = (Node) exp.evaluate(source, XPathConstants.NODE);
node.getParentNode().removeChild(node);
answered 2011-08-11T16:29:06.383

Your Answer