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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
MortenSlotKristensenCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.