C# 无法删除XML中共享相同属性值的所有元素
我想一次性删除所有同名元素。即使有多个同名元素,我当前的方法也会一次删除一个C# 无法删除XML中共享相同属性值的所有元素,c#,xml,linq,C#,Xml,Linq,我想一次性删除所有同名元素。即使有多个同名元素,我当前的方法也会一次删除一个 XDocument doc = XDocument.Load("D:\\test.xml"); var course = new XElement("Course", new XAttribute("Name", cname), new XAttribute("Code", ccode),
XDocument doc = XDocument.Load("D:\\test.xml");
var course = new XElement("Course",
new XAttribute("Name", cname),
new XAttribute("Code", ccode),
new XAttribute("Length", clenght));
doc.Element("Departments").Element("Department1").Add(course);
doc.Save("D:\\test.xml");
这是我当前的删除代码:
字符串sss是从文本框中获取的文本
remove(string sss)
XDocument doc = XDocument.Load("D:\\test.xml");
IEnumerable<XElement> elList =
from el in doc.Descendants("Deparment1").Elements("Course")
where el.Attribute("Name").Value == sss
select el;
// this should filter elements with same name attribute value
foreach (XElement el in elList)
{
el.Remove();
doc.Save("D:\\test.xml");
}
// this should remove them all and update the xml file
@Andrei V如果我将doc.save放在foreach之外,它不会改变这样认为。我看错了你的帖子。。。您是否检查了所选元素以查看它们是否被正确选择?删除之后呢?我个人认为xml没有正确地保存到文件中。元素被正确地选择,只是用计数器检查。在删除第一个元素后,它似乎会退出foreach。请尝试从foreach中获取保存,并按中所述保存文档。现在可以使用了。我用托利斯特;啊。。。在foreach中设置一个简单的断点可以为您节省很多麻烦。。。
doc.Descendants("Deparment1").Elements("Course")
.Where(el=>el.Attribute("Name").Value == sss)
.Remove();