I have this code:
XmlDocument doc = new XmlDocument();
doc.Load("file.xml");
XmlNodeList nodes = doc.SelectNodes("//myElement"); // Line 4
for (int i = 0; i < 5; i++) // Line 6
{
nodes[i].ParentNode.RemoveChild(nodes[i]);
}
doc.Save("output.xml");
If I put a breakpoint on line 4 the program works just fine. However, if I put a breakpoint on any line past that (such as 6), I get the object reference not set to instance of object
error because nodes only has one item in it.
The program crashes every time I run it without breakpoints. If I put a breakpoint on line 4 though, nodes has the proper count of 85
and everything works perfectly.
Even If I do Thread.Sleep(10000)
before and after line 4, the program still crashes because it only finds 1 node.
Does anyone know why this is?
Changed the code to this and now it works flawlessly, breakpoints or not, 100% of the time:
XDocument doc = XDocument.Load("file.xml");
List<XElement> nodes = doc.Descendants("myElement").ToList();
for (int i = 0; i < 5; i++)
{
nodes[i].Remove();
}
doc.Save("output.xml");
Not sure why SelectNodes
was giving me trouble but this solution seems to fix everything.