我尝试删除Xml中的元素,但目前只是删除“子元素” XML:
<dependency>
<dependentAssembly dependencyType="preRequisite">
</dependentAssembly>
</dependency>
<dependency>
<dependentAssembly dependencyType="install">
</dependentAssembly>
当前代码:
string filePath = "C:\\Example\\Example.exe.manifest"
var xml = XElement.Load(filePath);
xml.Descendants().Where(x => x.Name.LocalName == "dependentAssembly" && (string)x.Attribute("dependencyType") == "install").Remove();
xml.Save(filePath);
代码后的Xml:
<dependency>
<dependentAssembly dependencyType="preRequisite">
</dependentAssembly>
</dependency>
<dependency>
</dependency>
如您所见,我目前只是删除<dependentAssembly>
,但我尝试删除<dependency>
我该怎么做?
我从未在XML中做过那么多,所以我试着向你们学习:)
答案 0 :(得分:3)
两个选项。您可以选择要删除的父节点:
xml.Descendants()
.Where(x => x.Name.LocalName == "dependentAssembly" &&
(string)x.Attribute("dependencyType") == "install")
.Select(x => x.Parent)
.Remove();
或者您可以使用Any
查找包含此类孩子的元素:
xml.Descendants()
.Where(p => p.Elements()
.Any(x => x.Name.LocalName == "dependentAssembly" &&
(string)x.Attribute("dependencyType") == "install")))
.Remove();
我还强烈建议不匹配LocalName
,而是计算出你想要的完整名称空间限定元素名称,例如
XNamespace ns = "http://somenamespace";
xml.Descendants(ns + "dependency")
.Where(p => p.Elements(ns + "dependentAssembly")
.Any(x => (string)x.Attribute("dependencyType") == "install")))
.Remove();
答案 1 :(得分:1)
使用当前语句,您只需选择dependentAssembly节点并将dependency属性设置为install。你想要的是包含这样一个节点的父节点。因此,我建议将您的陈述修改为:
xml.Descendants().Where(x => x.Name.LocalName == "dependentAssembly" && (string)x.Attribute("dependencyType") == "install").Select(x => x.Parent).Remove();
我希望能解决你的问题。