issue removing a XDocument node based on its attribute

你。 提交于 2019-12-24 13:32:22

问题


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.


回答1:


Your code is looking for "CreditCards" with a name, not "CreditCard". You are also not using attributes anywhere in your sample document.

Try the following;

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



回答2:


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


来源:https://stackoverflow.com/questions/15612393/issue-removing-a-xdocument-node-based-on-its-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!