如何使用C#从XML文件中删除节点

可能重复:
如何从XmlNodeList中删除XmlNode

嗨,我如何从XML文件中删除一组节点。 这是一段代码片段。

string path = @"C:\Documents and Settings\e454935\Desktop\NUnitSettings.xml"; FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument(); xmldoc.Load(fs); fs.Close(); xmldoc.DocumentElement.RemoveChild(xmldoc.DocumentElement.ChildNodes[1]); FileStream WRITER = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite); xmldoc.Save(WRITER); WRITER.Close(); 

我尝试了以下代码只是为了删除一个节点并得到“对象引用未设置为对象的实例”。 在

 xmldoc.DocumentElement.RemoveChild(xmldoc.DocumentElement.ChildNodes[1]); 

这是一个示例XML文件,

           

实际上从这个文件我想删除具有值“a,b,c,d”的四个File1节点 ,然后我想添加一个节点

  

我怎样才能做到这一点。?

使用XPath定位要删除的节点可能更容易。 这个stackoverflow线程可能会给你一些想法。

在您的情况下,您将使用此表达式找到所需的四个节点:

 XmlDocument doc = new XmlDocument(); doc.Load(fileName); XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']"); 

您可以使用Linq to XML来执行此操作:

 XDocument doc = XDocument.Load("input.xml"); var q = from node in doc.Descendants("Setting") let attr = node.Attribute("name") where attr != null && attr.Value == "File1" select node; q.ToList().ForEach(x => x.Remove()); doc.Save("output.xml"); 

从XML中删除节点

  XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']"); for (int i = nodes.Count - 1; i >= 0; i--) { nodes[i].ParentNode.RemoveChild(nodes[i]); } doc.Save(path); 

在XML中为节点添加属性

  XmlDocument originalXml = new XmlDocument(); originalXml.Load(path); XmlNode menu = originalXml.SelectSingleNode("//Settings"); XmlNode newSub = originalXml.CreateNode(XmlNodeType.Element, "Setting", null); XmlAttribute xa = originalXml.CreateAttribute("name"); xa.Value = "qwerty"; XmlAttribute xb = originalXml.CreateAttribute("value"); xb.Value = "555"; newSub.Attributes.Append(xa); newSub.Attributes.Append(xb); menu.AppendChild(newSub); originalXml.Save(path); 

DocumentElementDocumentElement的根节点,因此该文档中不存在childNodes[1]childNodes[0]将是节点