Iteration over XML returns Same Node Over & Over

61 views Asked by At

The following is supposed to generate a list of all messages.

In practice I get a list of the rought length, but with the same element over and over.

Message is a class that get populated from the XmlNode sent to the constructor.

_messages = new List<Message>();
/*This does it*/
foreach (XmlNode n in thread.SelectNodes("//messages/message"))
{
    _messages.Add(new Message(n));
}
/*So does this*/
XmlNode msgItr = thread.SelectSingleNode("//messages").FirstChild;
while (msgItr != null)
{
    _messages.Add(new Message(msgItr));
    msgItr = msgItr.NextSibling;
}
1

There are 1 answers

1
ΩmegaMan On

You are pathing to the wrong location, just use //message.

Here is two ways of enumerating the nodes, I am using LinqPad which Dump() shows one the current state.

XDocument xd = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Messages",   
         new XElement("Message", "Alpha"),
         new XElement("Message", "Beta"),
         new XElement("Message", "Omega")
  ));

  xd.Descendants("Message").Dump("XDocument");

  XmlDocument xmd = new XmlDocument();

  xmd.LoadXml(xd.ToString());

  xmd.SelectNodes("//Message")
     .Dump("XmlDocument");

Here is the results for the first and second dumps

enter image description here