17

我有一个如下所示的 xml 文档:

<Applications>
  <myApp>
    <add key="ErrorDestinationEventLog" value="EventLog" />
    <add key="version" value="5.0.0.0" />
    <add key="DebugMode_RUN" value="true" />
  </myApp>
</Applications>

所有元素具有相同的元素名称但不同的属性。如何使用 C# 中的 XDocument 从此 xml 中删除一个特定元素及其属性?

xd.Element("Applications").Element("myApp").Element(xe.Name).RemoveAll();

上述命令不起作用,因为所有元素都具有相同的名称。

除了名称之外,还有什么方法可以识别元素吗?如果是这样,我如何使用它从 XDocument 中删除它?

4

2 回答 2

33
string key = "version";
XDocument xdoc = XDocument.Load(path_to_xml);
xdoc.Descendants("add")
    .Where(x => (string)x.Attribute("key") == key)
    .Remove();

更新您几乎完成了这项工作。您错过的是按属性值过滤元素。这是您过滤和删除选定元素的代码:

xd.Element("Applications")
  .Element("myApp")
  .Elements("add")
  .Where(x => (string)x.Attribute("key") == key)
  .Remove();
于 2012-12-05T20:02:57.230 回答
4
xd.Descendants("add")
    .First(a => a.Attribute("key").Value == "version")
    .Remove();

如果您有除myAppunder contains 以外Applications的标签add,您可能更喜欢更安全的版本

xd.Descendants("myApp").First()
    .Descendants("add")
    .Where(x => (string)x.Attribute("key") == "version")
    .Remove();

您还可以使用XPath (System.Xml.XPath)

string key="version";
xd.XPathSelectElement(String.Format("//myApp/add[@key='{0}']",key)).Remove();
于 2012-12-05T20:04:52.243 回答