Loop Through XML Child Nodes and Retrieve Name and Value

If I have the following XML

<site>
<foo>true</foo>
<bar>true</bar>
</site>

How do i loop through all the child nodes in <site> and then programatically get the name of the child node and the innerXML? (ex. Foo and true)  I'd like to use a nodelist if possible.
davidcahanAsked:
Who is Participating?
 
MortenSlotKristensenConnect With a Mentor Commented:
And if you would like the NodeList:
XmlElement root = xmlDoc.DocumentElement;
XmlNodeList elements = root.ChildNodes;
 
for(int i = 0; i < elements.Count; i++)
    Console.WriteLine("Name: {0}, InnerXml: {1}", elements[i].Name, elements[i].InnerXml);

Open in new window

0
 
MortenSlotKristensenCommented:
Something like this should work:
string xmlstr = @"<site><foo>true</foo><bar>true</bar></site>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstr);
XmlNode root = doc.DocumentElement;
IEnumerator ienum = root.GetEnumerator();
 
while (ienum.MoveNext()) {     
    XmlNode site = (XmlNode) ienum.Current;
    IEnumerator ienum2 = site.GetEnumerator();
 
    while (ienum2.MoveNext()) {
        XmlNode elm = (XmlNode) ienum2.Current;
        Console.WriteLine("Name: "+elm.Name);
        Console.WriteLine("InnerXml: "+elm.InnerXml);
        Console.WriteLine();
    }
 }

Open in new window

0
 
MortenSlotKristensenCommented:
Now that I think about it.. This is sufficient:
string xmlstr = @"<site><foo>true</foo><bar>true</bar></site>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstr);
XmlNode root = doc.DocumentElement;
IEnumerator ienum = root.GetEnumerator();
while (ienum.MoveNext()) {
   XmlNode elm = (XmlNode) ienum.Current;
   Console.WriteLine("Name: "+elm.Name);
   Console.WriteLine("InnerXml: "+elm.InnerXml);
   Console.WriteLine();
}

Open in new window

0
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.

All Courses

From novice to tech pro — start learning today.