想删除xpath匹配到的节点,就需要父节点的RemoveChild方法,但是xpath匹配到的节点找不到其父节点,其父节点也找不到它。
public int Delete(string where="")
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlElement root = xmlDoc.DocumentElement;
XmlNodeList recordNodes;
if (where == "") recordNodes = root.GetElementsByTagName("record");
else
{
string xpath = "/data" + "/record[" + where + "]/*/parent::*";
recordNodes = root.SelectNodes(xpath);
}
while (recordNodes.Count > 0)//一边删索引会跟着变,所以用while
{
root.RemoveChild((XmlElement)recordNodes[0]);
//((XmlElement)recordNodes[0]).ParentNode.RemoveChild(recordNodes[0]);
}
xmlDoc.Save(path);
return recordNodes.Count;
}
注释掉的部分parentNode会报空指针异常
怎么找到父节点,或者怎么删除selectNode(xpath)匹配到的节点