Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Parsing XML using LINQ

Posted on 2011-09-21
5
Medium Priority
?
269 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 1200 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 800 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

Give Your Engineering Team a Productivity Boost

Learn why container technology is so powerful and how it can provide your team with productivity gains and other benefits.

Question has a verified solution.

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

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…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

715 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