正如我在标题中所说: 我想用c#删除Xml-File中的整个元素,如果该元素的属性值是preRequisite。
XML文件:
<dependency>
<dependentAssembly dependencyType="preRequisite"></dependentAssembly>
</dependency>
<dependency>
<dependentAssembly dependencyType="install"></dependentAssembly>
</dependency>
当前代码:
using (XmlReader reader = XmlReader.Create(filePath))//filepath is just a normal Path
{
while (reader.Read())
{
if (reader.Name == "dependentAssembly" && reader.GetAttribute("dependencyType") != "preRequisite")
{
//here shall it delete the Element "dependency"
}
}
}
在我设置命令的地方,它将删除元素&#34;依赖&#34;
我尝试了很多东西,但我不明白我将如何删除这个元素
答案 0 :(得分:2)
您可以使用LINQ to XML:
实现此目的var xml = XElement.Load(File.OpenRead(@"XmlLocation"));
var elementsToDelete =
xml.Descendants("dependentAssembly")
.Where(x => x.Attribute("dependencyType") != null &&
x.Attribute("dependencyType").Value != "preRequisite");
foreach (var xElement in elementsToDelete)
{
xElement.Remove();
}