从XML中删除整个记录

时间:2014-04-03 06:50:05

标签: android xml xpath nodelist

我正在尝试使用XPath从XML文件中删除节点及其子节点。这是我尝试过但不起作用的。

这是xml:

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

我通过搜索该电子邮件的特定记录然后将其删除来获取用户的电子邮件地址。

以下是代码:

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

以下是我得到的例外情况:

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

1 个答案:

答案 0 :(得分:2)

应该是

cNode.getParentNode().removeChild(cNode);

nod.removeChild(cNode);

让我们说Anod的父节点。您目前要做的是从cNode删除孩子A,而您想从cNode

删除孩子nod

<强>更新

如果要删除整个<user/>记录,则代码可以简单得多。无需手动删除每个子元素。

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);
相关问题