【问题标题】:delete specific child from xml document从 xml 文档中删除特定子项
【发布时间】:2020-06-09 01:14:30
【问题描述】:

我有一个如下所示的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");

问候。

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: c# .net xml linq-to-xml


【解决方案1】:

你可以试试 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多