从 xml 文档中删除特定的 child

delete specific child from xml document

我有一个 xml 文件,如下所示

    <?xml version="1.0" encoding="utf-8"?>
   <ArrayOfEtiquette xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Etiquette>
     <BgColor>#8075D1C5</BgColor>
     <BorderColor>#FF4E5B6F</BorderColor>
     <AssociatedAffaireId>
       <string>d4689f33-5600-47fe-883d-efcbf5e469c2</string>
       <string>203cc4a8-8c24-4a2d-837c-29c7c1f73007</string>
       <string>1bae35dd-d501-4d87-bdd4-147fc0ba29d2</string>
     </AssociatedAffaireId>
     <Label>Ouverte</Label>
    </Etiquette>
   </ArrayOfEtiquette>

我只需要删除

<string>203cc4a8-8c24-4a2d-837c-29c7c1f73007</string>

这是我试过的代码,但它不起作用,

    XDocument xmlSettings = XDocument.Load(chemin + "\Etiquettes.xml");

    if(xmlSettings.ToString().Contains(aff.Id))
   {
     string newXmlSettings =  xmlSettings.ToString().Replace("<string>" + 
     aff.Id+ "</string>","");
   }
        xmlSettings.Save(chemin + "\Etiquettes.xml");

此致。

您可以尝试使用 LINQ

//load the xml
var xdoc = XDocument.Load(filePath);
//find and remove
xdoc.Descendants("string")
    .Where(x => x.Value == "203cc4a8-8c24-4a2d-837c-29c7c1f73007")
    .Remove();    
//save it back 
xdoc.Save(filePath);