質問

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.

役に立ちましたか?

解決

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);

他のヒント

To get that node you can use XPath:

/a/b[foo[text() = 'null']]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top