Solved

Parsing XML using LINQ

Posted on 2011-09-21
5
248 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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

758 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now