Solved

Parsing XML using LINQ

Posted on 2011-09-21
5
254 Views
Last Modified: 2013-12-17
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?
0
Comment
Question by:ChrisMDrew
5 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 36578019
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

0
 
LVL 16

Accepted Solution

by:
Easwaran Paramasivam earned 300 total points
ID: 36578403
I hope your problem selecting subnodes (patches) as well. I've came accross the same kind of problem and you could find your solution there.

 http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_27305052.html?cid=1135#a36535232

Good luck!!
0
 
LVL 3

Assisted Solution

by:nixkuroi
nixkuroi earned 200 total points
ID: 36578570
First set up your classes like this:

        public class Patch
        {
            public int ID { get; set; }
            public string Status { get; set; }
            public string SurfaceID { get; set; }
        }

        public class Job
        {
            public string Address { get; set; }
            public string PostCode { get; set; }
            public List<Patch> Patches = new List<Patch>();
        }

Open in new window


Then, you can read your xml and parse it into your List<Job> like this:

XElement jobsElem= XElement.Parse("<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>");

List<Job> Jobs = new List<Job>();
jobsElem.Elements("job").ToList().ForEach(f =>
{

    string postcode = (f.Attribute("postcode") != null && !String.IsNullOrWhiteSpace(f.Attribute("postcode").Value)) ? f.Attribute("postcode").Value : string.Empty;
    string address = (f.Attribute("address") != null && !String.IsNullOrWhiteSpace(f.Attribute("address").Value)) ? f.Attribute("address").Value : string.Empty;
    Job job = new Job() { Address = address, PostCode = postcode };
    if (f.HasAttributes)
    {
        f.Elements("patch").ToList().ForEach(p =>
        {
            int id = 0;
            if (p.Attribute("id") != null && !String.IsNullOrWhiteSpace(p.Attribute("id").Value))
                Int32.TryParse(p.Attribute("id").Value, out id);
            string status = (p.Attribute("status")!=null && !String.IsNullOrWhiteSpace(p.Attribute("status").Value))? p.Attribute("status").Value: string.Empty;
            string surfaceid = (p.Attribute("surface_id") != null && !String.IsNullOrWhiteSpace(p.Attribute("surface_id").Value)) ? p.Attribute("surface_id").Value : string.Empty;
            job.Patches.Add(new Patch() { ID = id, Status = status, SurfaceID = surfaceid });
        });
    }
    Jobs.Add(job);
});

Open in new window

0
 
LVL 5

Expert Comment

by:Jeroen Timmermans
ID: 36579068
Another route is to serialize the XML to the Job-object.
0
 

Author Closing Comment

by:ChrisMDrew
ID: 36579207
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.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
jquery progress bar 3 40
Regular expression help 2 24
REXEX help Part 2 2 22
VB.Net - MemoryMappedFiles - Confirm receipt 2 18
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question