r wank
r wank

Reputation: 352

issue removing a XDocument node based on its attribute

I'm trying to remove a CreditCard node in a XDocument called doc based on its name attribute but its not working as intended.

doc is my XDocument and it looks like this:

XDocument doc = new XDocument(
                new XComment("XML test file"),
                new XElement("CreditCards",
                    new XElement("CreditCard",
                        new XAttribute("Name", "TestCard1"),
                        new XAttribute("phoneNumber", 121212142121)),
                    new XElement("CreditCard",
                        new XAttribute("Name", "TestCard2"),
                        new XAttribute("phoneNumber", 6541465561)),
                    new XElement("CreditCard",
                        new XAttribute("Name", "TestCard3"),
                        new XAttribute("phoneNumber", 445588))
                )
            );

This is the query I try to run but it doesn't remove the node. name is a string I pass to this function as a reference to tell it what to delete

var q = from node in doc.Descendants("CreditCards")
                        let attr = node.Attribute("name")
                        where attr != null && attr.Value == name
                        select node;
q.ToList().ForEach(x => x.Remove());

I don't get any errors with this, but nothing is deleted either.

Upvotes: 1

Views: 2518

Answers (2)

Chris McAtackney
Chris McAtackney

Reputation: 5222

Your code is looking for "CreditCards" with a name, not "CreditCard".

Try the following;

doc.Descendants("CreditCard")
   .Where(x => (string)x.Attribute("Name") == name)
   .Remove();

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

You have lowercase name of attribute in your query name. But in your xml name of attribute is Name. Xml is case sensitive. Also attribute Name is a child of CreditCard element, not of CreditCards elements:

doc.Descendants("CreditCards")
   .Elements()
   .Where(c => (string)c.Attribute("Name") == name) 
   .Remove();

Upvotes: 2

Related Questions