C# 当我们有多个名称相同但属性不同的元素时,如何使用 Xdocument 从 xml 中删除元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13731374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove an element from an xml using Xdocument when we have multiple elements with same name but different attributes
提问by naren.katneni
I have an xml document which looks like this:
我有一个 xml 文档,如下所示:
<Applications>
<myApp>
<add key="ErrorDestinationEventLog" value="EventLog" />
<add key="version" value="5.0.0.0" />
<add key="DebugMode_RUN" value="true" />
</myApp>
</Applications>
All the elements have same element name but different attributes. How do I remove one particular element and it's attributes from this xml using XDocument in C#?
所有元素具有相同的元素名称但具有不同的属性。如何使用 C# 中的 XDocument 从此 xml 中删除一个特定元素及其属性?
xd.Element("Applications").Element("myApp").Element(xe.Name).RemoveAll();
The above command is not working as all the elements have same name.
上述命令不起作用,因为所有元素都具有相同的名称。
Is there any way to identify an element with, other than it's name? And if so, how can I use this to remove it from the XDocument?
除了名称之外,还有什么方法可以识别元素?如果是这样,我如何使用它从 XDocument 中删除它?
采纳答案by Sergey Berezovskiy
string key = "version";
XDocument xdoc = XDocument.Load(path_to_xml);
xdoc.Descendants("add")
.Where(x => (string)x.Attribute("key") == key)
.Remove();
UPDATEYou almost did the job. What you missed is filtering elements by attribute value. Here is your code with filtering and removing selected elements:
更新你几乎完成了这项工作。您错过的是按属性值过滤元素。这是过滤和删除选定元素的代码:
xd.Element("Applications")
.Element("myApp")
.Elements("add")
.Where(x => (string)x.Attribute("key") == key)
.Remove();
回答by L.B
xd.Descendants("add")
.First(a => a.Attribute("key").Value == "version")
.Remove();
If you have tags other than myAppunder Applicationscontaining add, you may prefer a safer version
如果你有比其他标签myApp下Applications包含add,你可能更喜欢一个更安全的版本
xd.Descendants("myApp").First()
.Descendants("add")
.Where(x => (string)x.Attribute("key") == "version")
.Remove();
You can also use XPath(System.Xml.XPath)
您还可以使用XPath(System.Xml.XPath)
string key="version";
xd.XPathSelectElement(String.Format("//myApp/add[@key='{0}']",key)).Remove();

