Wednesday, February 17, 2010

Looping through XML

Code snippet for transforming an XML Document to an XDocument (I got this from another blog, though I've lost the link - google and you shall probably find). I didn't end up using it as I decided to work with XMLNodeLists. Personal project so performance is not an issue (if it's taking too long, I'll fix it)

       private static XDocument DocumentToXDocumentReader(XmlDocument doc)
        {
            return XDocument.Load(new XmlNodeReader(doc));
        }

Looping through XML Nodes ... one solution.Get the repeating nodes and set them to a nodelist. Loop through the nodelist using foreach function.

WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
doc.Load(response.GetResponseStream());
XmlNodeList nodelist = doc.GetElementsByTagName("Item");
int i = 0;

foreach (XmlNode item in nodelist)
{
 // Do stuff like string temp = item.ChildNodes.Item(3).InnerText;
// In my case I'm passing the data from the XML payload into a list of objects
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.