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

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

I have an xml document which looks like this:


  
    
             


        
2条回答
  •  情话喂你
    2021-01-07 23:59

    xd.Descendants("add")
        .First(a => a.Attribute("key").Value == "version")
        .Remove();
    

    If you have tags other than myApp under Applications containing add, you may prefer a safer version

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

    You can also use XPath (System.Xml.XPath)

    string key="version";
    xd.XPathSelectElement(String.Format("//myApp/add[@key='{0}']",key)).Remove();
    

提交回复
热议问题