Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a node using xpath

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.

like image 404
rgamber Avatar asked Feb 17 '14 21:02

rgamber


People also ask

How do you delete a node in XML?

To remove a node from the XML Document Object Model (DOM), use the RemoveChild method to remove a specific node. When you remove a node, the method removes the subtree belonging to the node being removed; that is, if it is not a leaf node.

What does node () do in xpath?

node() matches any node (the least specific node test of them all) text() matches text nodes only. comment() matches comment nodes. * matches any element node.


1 Answers

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);
like image 130
Ian Roberts Avatar answered Sep 21 '22 10:09

Ian Roberts