如何从XML文件中使用C#删除节点 [英] How to delete node from XML file using C#
问题描述
可能重复:
的如何从XmlNodeList中
我怎么能删除删除一个XmlNode从XML文件的一组节点。?
下面的代码片段
Hi, How can i delete a set of nodes from an XML file.? Here is a code snippet.
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();
我尝试下面的代码只删除一个节点,并得到了
对象未设置为一个对象的一个实例。在
I tried the following code simply to delete a node and got "Object reference not set to an instance of an object." at
xmldoc.DocumentElement.RemoveChild(xmldoc.DocumentElement.ChildNodes[1]);
下面是一个简单的XML文件,
Here is a sample XML file,
<?xml version="1.0"?>
<Xml1>
<Settings>
<Setting name="DisplayFormat" value="Full" />
<Setting name="File1" value="a" />
<Setting name="File1" value="b" />
<Setting name="File1" value="c" />
<Setting name="File1" value="d" />
</Settings>
</Xml1>
其实从这个文件我想删除四个文件1节点有值A,b,C,D,然后我想添加节点
Actually from this file i want to delete the Four File1 nodes which has the values "a,b,c,d" and then i want to add a node,
<Setting name="File1" value="e" />
我怎样才能做到这一点?
How can i do this.?
推荐答案
这可能是更容易使用XPath找到要删除的节点。 这个计算器线程可能会给你一些想法。
It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.
在你的情况,你会发现,你想用这种表达的四个节点:
In your case you will find the four nodes that you want using this expression:
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
这篇关于如何从XML文件中使用C#删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!