RSS

Reading an XML file using Linq to XML

22 Jun

A quick and post and more for my own reference but I recently needed to read some elements from an XML document which can be accomplished much easier these days using Linq to XML.

So if I have a simple XML document :

Sample XML document

I can read this using Linq as below (language is C#) :

C# routine to parse the XML document using Linq

In this method I am first loading the XML file into an XDocument Object found under the System.XML.Linq namespace.

I am then using Linq to return a collection of Items which represent the Parent ‘Client’ Nodes, using the Descendants function.

Then we can loop though each Client Node and simply extract the Element Values for the KEY and POSITION Nodes.  Its also worth noticing in this example that I have included an attribute at the CLIENT Node level.  Using Attributes().First() I am requesting the first attribute found attached to my CLIENT object.

Like I mentioned nothing difficult here but a handy little reference

Advertisements
 
Leave a comment

Posted by on June 22, 2012 in C#, Linq, Uncategorized, XML

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: