可能重复:
如何从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();
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下代码来删除一个节点并获得"对象引用未设置为对象的实例".在
xmldoc.DocumentElement.RemoveChild(xmldoc.DocumentElement.ChildNodes[1]);
Run Code Online (Sandbox Code Playgroud)
这是一个示例XML文件,
<?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>
Run Code Online (Sandbox Code Playgroud)
实际上从这个文件我想删除四个File1节点,其值为"a,b,c,d",然后我想添加一个节点,
<Setting name="File1" value="e" />
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点.?
idu*_*sun 26
您可以使用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");
Run Code Online (Sandbox Code Playgroud)
从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);
Run Code Online (Sandbox Code Playgroud)
在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);
Run Code Online (Sandbox Code Playgroud)
使用XPath定位要删除的节点可能更容易.这个stackoverflow线程可能会给你一些想法.
在您的情况下,您将使用此表达式找到所需的四个节点:
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
115411 次 |
| 最近记录: |