Link to home
Start Free TrialLog in
Avatar of ChrisMDrew
ChrisMDrew

asked on

Parsing XML using LINQ

Just started using LINQ as it seems very powerful at the moment but a little difficult to get in to.  Consider the following XML...

<?xml version="1.0"?>
<whereabouts date="15/9/2011" gangid="GB">
<job postcode="SG5 1EH" address="my address">
<patch id="25168" status="" surface_id="6mm Ashpalt" />
<patch id="25169" status="" surface_id="6mm Ashpalt" />
</job> 
<job postcode="SG5 2EH" address="17 High Street" >
<patch id="25198" surface_id="6mm Ashpalt />
<patch id="25199" surface_id="6mm Ashpalt/>
</job>
</whereabouts>

Open in new window


I have an object Job which contains a List<Patch> where Patch is another object.  Firstly I want to be able to read just the 'whereabouts' node so that I can perform a quick sanity check - how do you select a single node like this?

Secondly I would like to read all of the jobs and patches into objects.  I know that I could do something like :-

 
List<Job> jobs =
	(from job in xmlDoc.Descendants("job")
	select new Job
	{
	Postcode = job.Element("postcode").Value,
	Address = job.Element("address").Value,
	}).ToList<Job>();

Open in new window


To read the jobs into a list of <Job> objects but is it possible to read the 'Patches' sub-nodes and directly populate the list of patches within each job?  If not how can I associate the patches with the job?
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

I believe that you are looking for something like this:


List<Job> jobs =
	(from job in xmlDoc.Descendants("job")
	select new Job
	{
    	    Postcode = job.Element("postcode").Value,
	    Address = job.Element("address").Value,
            PatchList = job.Elements("patch"),
	}).ToList<Job>();

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Easwaran Paramasivam
Easwaran Paramasivam
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Another route is to serialize the XML to the Job-object.
Avatar of ChrisMDrew
ChrisMDrew

ASKER

Thanks to all - this has made my business object very easy to generate from the XML.  Adding checks to ensure that the attributes exist is definately a good idea also.