简体   繁体   中英

delete specific child from xml document

i have an xml file that as shown below

    <?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>

I need to delete only

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

this is the code i tried, but its not working,

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

Regards.

You can try with 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM