0

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;
1
  • can you please add sample xml Commented Nov 6, 2020 at 12:44

2 Answers 2

1

try this

doc.Descendants("Object")
   .Where(x=> x.Attribute("Deleted").Value == "true")
   .ToList()
   .ForEach(x => x.Remove());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your quick answer. Unfortunately this throws an exception due to XElement object not having a ToList() method
using System.Linq;
0

Removing the .FirstOrDefault() from my code resolved my issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.