C# 通过了解属性值删除嵌套XML中的*元素
假设我有以下XML:C# 通过了解属性值删除嵌套XML中的*元素,c#,C#,假设我有以下XML: <Chapter Name="Introduction" > <Overview caption="Simple" > <Property name="ElementID" value="1" /> <Property name="Summary" value="no" /> <Overview caption="Simple" > <
<Chapter Name="Introduction" >
<Overview caption="Simple" >
<Property name="ElementID" value="1" />
<Property name="Summary" value="no" />
<Overview caption="Simple" >
<Property name="ElementID" value="2" />
</Overview>
<Property name="ElementID" value="37" />
<Property name="ElementID" value="38" />
<Property name="Summary" value="no" />
</Overview>
</Overview>
</Overview>
</Chapter>
我需要使用C#使用LinqToXml删除所有具有value=“ElementID”的属性[name]的节点/元素
var doc = XDocument.Load("YourFile");
var q = doc.Descendants().Where(x => x.Attribute("Name") != null && "ElementID" == (string)x.Attribute("values"));
foreach (var item in q) item.Remove();
doc.Save("YourFile");
到目前为止,您尝试了哪些代码?请检查您的示例。XML代码不一致。如果使用的是
(string)x.Attribute(“values”)
,则不需要使用.Value
ForEach&&RemoveAll?若要删除选定的元素,“我需要删除所有节点/元素都有属性…”
RemoveAll不删除元素本身,只删除子体。改用Removebut我还有
var doc = XDocument.Load("YourFile");
var q = doc.Descendants().Where(x => x.Attribute("Name") != null && "ElementID" == (string)x.Attribute("values"));
foreach (var item in q) item.Remove();
doc.Save("YourFile");
var query = root.Descendants()
.Where(x => (string)x.Attribute("name") == "ElementID")
.ToList()
.ForEach( (x) => x.RemoveAll());
root.Save(path);