简体   繁体   中英

C# Remove XML elements based on attribute value

Would really appreciate some help with this one. The below code removes an element from an XML if it contains the Deleted = true attribute. This works perfectly fine except it only removes the first match. I would like it to remove ALL the Object elements with the attribute condition Deleted = true

        public static string TestMethod1(string xmlpath)
    
        XmlDocument xmlfile = new XmlDocument();
        xmlfile.Load(xmlpath);
        string xmlcontents = xmlfile.InnerXml;

        XDocument doc = XDocument.Parse(xmlcontents);

        doc.Descendants("Object")
            .Where(x => x.Attribute("Deleted").Value == "true").FirstOrDefault()
            .Remove();

        doc.Save(outputpath);
        string docstring = doc.ToString();
        return docstring;

try this

doc.Descendants("Object")
   .Where(x=> x.Attribute("Deleted").Value == "true")
   .ToList()
   .ForEach(x => x.Remove());

从我的代码中删除 .FirstOrDefault() 解决了我的问题。

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