Remove a node using xpath

25,572

Solution 1

doc.removeChild(node);

will not work because the node you're trying to remove isn't a child of the document node, it's a child of the document element (the a), which itself is a child of the document root node. You need to call removeChild on the correct parent node:

node.getParentNode().removeChild(node);

Solution 2

To get that node you can use XPath:

/a/b[foo[text() = 'null']]
Share:
25,572
rgamber
Author by

rgamber

Updated on February 18, 2020

Comments

  • rgamber
    rgamber over 4 years

    I have an xml structure as follows:

    <a>
       <b>
          <foo>null</foo>
       </b>
       <b>
          <foo>abc</foo>
       </b>
       <b>
          <foo>efg</foo>
       </b>
    </a>
    

    I am using org.w3c.dom.Document to update the nodes. when <foo> has a value null, I want to remove

    <b>
      <foo>null</foo>
    </b>
    

    Is this possible? I know I can call removeChild(childElement), but not sure how I can specify to remove the specific nested element above.

    Update: With the answer below, I tried:

    String query = "/a/b[foo[text() = 'null']]";
    Object result = (xpath.compile(newQuery)).evaluate(doc, NODE);
    NodeList nodes = (NodeList)result;
    for (int i = 0; i < nodes.getLength(); i++)
    {
        Node node = nodes.item(i);
        doc.removeChild(node);
    }
    

    I get NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.

  • rgamber
    rgamber over 10 years
    Yes, I can do that. But if I call removeChild on that, will it remove just the <foo>null</foo>, or <b><foo>null</foo></b>. Also I don't want to touch the root node <a>.
  • Kirill Polishchuk
    Kirill Polishchuk over 10 years
    According to tour question you want to remove <b> <foo>null</foo> </b>, right?
  • rgamber
    rgamber over 10 years
    yes. I was thinking this query will also try to remove/modify <a>
  • rgamber
    rgamber over 10 years
    Thanks for your time. I am trying with the new query, but I am still getting an error. Any suggestions?