簡體   English   中英

當我們有多個具有相同名稱但屬性不同的元素時,如何使用Xdocument從xml中刪除元素

[英]How to remove an element from an xml using Xdocument when we have multiple elements with same name but different attributes

我有一個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中刪除它?

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();
xd.Descendants("add")
    .First(a => a.Attribute("key").Value == "version")
    .Remove();

如果您在包含add Applications下有myApp以外的標簽,您可能更喜歡更安全的版本

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM