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

前端 未结 2 1531
野的像风
野的像风 2021-01-07 23:38

I have an xml document which looks like this:


  
    
             


        
2条回答
  •  北海茫月
    2021-01-08 00:03

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

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

提交回复
热议问题