Reputation: 87
As I said in the Title: I'm trying to delete a specific XML node(in c#).
so I researched and found this:
XmlDocument xmlDoc = new XmlDocument();
XmlNode nodeToDelete = xmlDoc.SelectSingleNode("/root/XMLFileName[@ID="+nodeId+"]");
if (nodeToDelete != null)
{
nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
}
xmlDoc.Save("XMLFileName.xml")
I understand here that he's targeting a specific node ( in this case "[@ID ="+nodeId+
)
Ok, my question is can I do the same just in the opposite way, by that I mean if its not nodeId
then delete it (just like the "!="-Operator in C#).
Upvotes: 0
Views: 447
Reputation: 3713
First of all, the code you posted uses SelectSingleNode
which will allways return only one node.
First thing to do : using SelectNodes
whose doc is here.
THe result would be :
List<XmlNode> nodes = new List<XmlNode>(
xmlDoc.SelectNodes("//root/XMLFileName[@ID!="+nodeId+"]")
.Cast<XmlNode>());//execute the query and put it into a list
// as my list is strongly typed, I **must** use cast method
// thanks to this list, I can modify the document without changing the
// collection that foreach is traversing
foreach(var nodeToDelete in nodes){
if (nodeToDelete != null)
{
nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
}
}
xmlDoc.Save("XMLFileName.xml")
You can also use a linq query as you are in C# as explained here.
Upvotes: 2