I have a xml config file that I am trying to remove a node from. My xml document is as follows
<appSettings>
<add key="value1" value="27348614" />
<add key="value2" value="123432" />
<add key="removeMe" value="removeMeAsWell" />
</appSettings>
I have tried the following method
public void removeNode(XDocument AppStoreXML, string FOPath)
{
var newElement = new XElement("add",
new XAttribute("key","removeMe" ),
new XAttribute("value", "removeMeAsWell"));
AppStoreXML.Root.Descendants("appSettings")
.First(s => s.Attribute("key").Value == "removeMe")
.Remove(); //this returns the error Sequence contains no matching element
//newElement.Remove(); this try returns no matching parent
AppStoreXML.Save(FOPath);
}
Anyone have any idea what I am doing wrong?
This is the problem:
AppStoreXML.Root.Descendants("appSettings")
You're trying to find descendant elements of appSettings
which are also called appSettings
and have the specified attributes. You want the add
elements instead:
AppStoreXML.Root.Descendants("add")
Also, you might want to change First()
to Where
- that way you can find multiple elements to remove if you want to.
See more on this question at Stackoverflow