Domanda

I am trying to delete a node and its children from an XML file using XPath. Here is what I tried but its not working.

Here is the xml:

<registration>
   <users>
     <name>abc</name>
     <class>10th</class>
     <email>demo@mail.com</email>
   </users>
</registration>

I am getting an email address from a user by searching the specific record for that email and then deleting it.

Here is the code:

XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//email[text()='" + sEmail + "']";
System.out.println(expression);
Node node = (Node) xPath.compile(expression).evaluate(xmlDocument,XPathConstants.NODE);
if (null != node) {
  Node pNode = node.getParentNode();
  nodeList = pNode.getChildNodes();
  for (int i = 0; null != nodeList && i < nodeList.getLength(); i++) {
    Node nod = nodeList.item(i);
    if (nod.getNodeType() == Node.ELEMENT_NODE) {
      System.out.println(nod.getNodeName() + " : "nod.getFirstChild().getNodeValue());
      Node cNode = nod.getFirstChild();
  nod.getParentNode().removeChild(cNode);                
    }
  }
}

Here is the exception I get:

04-03 15:39:18.274: E/AndroidRuntime(23163):    at org.apache.harmony.xml.dom.InnerNodeImpl.removeChild(InnerNodeImpl.java:181)
È stato utile?

Soluzione

It should be

cNode.getParentNode().removeChild(cNode);

or

nod.removeChild(cNode);

Lets say A is the parent node of nod. What you are currently trying to do is to delete the child cNode from A, whereas you want to remove the child cNode from nod

Update

If you want to delete the whole <user/> record than your code can be much simpler. No need for deleting each and everyone child element by hand.

XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//user[email='" + sEmail + "']";
System.out.println(expression);
Node node = (Node) xPath.compile(expression).evaluate(xmlDocument,XPathConstants.NODE);
if (node != null) node.getParentNode().removeChild(node);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top