• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2112
  • Last Modified:

Looping through elements in XML

Hi - I am trying to loop through an xml string as shown in listing A.

When I try run the code in Listing B, I only get the details of the FIRST node (UNH) in the XML displayed, not the rest, like UCM, UNT etc.

Why is this and how do I get the thing to display all nodes??
I suspect its because the nodes have different names?
But surely there must be a away to get all nodes with DIFFERENT names?

Please help

//Listing A
incomingMessage = @"
    <untTotal>135 000 000</untTotal>
    <untTotal>35 000 000</untTotal>
    <untTotal>100 000 000</untTotal>
    <untTotal>100 000</untTotal>
    <untTotal>20 000</untTotal>
//Listing B
            XmlNodeList xmlnode = xmlIn.SelectNodes("EdiMessage");
            for (int i = 0; i < xmlnode.Count; i++)
                XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;
                Console.WriteLine(":\t" + xmlnode[i].FirstChild.InnerText);

Open in new window

2 Solutions
Since "EditMessage" is your ROOT node, use this instead:
XmlNodeList xmlnode = xmlIn.FirstChild.ChildNodes;
There is only 1 EdiMessage, which is why you only get one node.  Once you get that node, you can just loop through its children, like so:

XmlNode node = xmlIn.SelectSingleNode("EdiMessage");
for (int i = 0; i < node.ChildNodes.Count; i++)
     XmlAttributeCollection xmlattrc = node.ChildNodes[i].Attributes;
     Console.WriteLine(":\t" + node.ChildNodes[i].FirstChild.InnerText);

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now