[英]How to delete a node from a xml c#?
I have a xml structure like this:- 我有这样的xml结构:-
<Person id="1" Name="Rahul lamba" Manager_Id="13" Department="IT" />
<Person id="6" Name="Saurabh" Manager_Id="4" Department="IT" />
<Person id="5" Name="Amitesh" Manager_Id="6" Department="IT" />
Now I want to delete Manager_Id node from XML from every line. 现在,我想从每行XML中删除Manager_Id节点。
I tried this but nothing works out 我尝试了这个,但没有任何效果
XmlNodeList l = doc.GetElementsByTagName("Person");
foreach (XmlNode item in l)
{
foreach (var item1 in item.ChildNodes)
{
if (item1 == "Manager_Id")
{
//Code to remove Manager_Id node.
}
}
}
How can i achieve this? 我怎样才能做到这一点?
Thanx in advance. 提前感谢。
You can do it easily with Linq To Xml, 您可以使用Linq To Xml轻松完成此操作,
var xDoc = XDocument.Parse(xmlstring); //XDocument.Load(filename)
xDoc.Descendants("Person")
.Select(x => x.Attribute("Manager_Id"))
.Where(x => x!=null)
.ToList().ForEach(a => a.Remove());
var newxml = xDoc.ToString(); //xDoc.Save(fileName);
XmlTextReader reader = new XmlTextReader(@"C:\MyXml.xml");
reader.Read();
XmlDocument doc = new XmlDocument();
doc.Load(reader);
XmlNode node = doc.SelectSingleNode("/Persons/Person[@Manager_Id=6]");
node.ParentNode.RemoveChild(node);
reader.Close();
doc.Save(@"D:\MyXml.xml");
removing all nodes with att 用att删除所有节点
XmlTextReader reader = new XmlTextReader(@"C:\MyXml.xml");
reader.Read();
XmlDocument doc = new XmlDocument();
doc.Load(reader);
XmlNodeList lstNode = doc.SelectNodes("/Persons/Person[@Manager_Id]");
foreach (XmlNode node in lstNode)
{
node.ParentNode.RemoveChild(node);
}
reader.Close();
doc.Save(@"C:\MyXml.xml");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.