Link to home
Start Free TrialLog in
Avatar of ChrisMDrew
ChrisMDrew

asked on

Parse XML using LINQ

I have an XML document which has been sent via a web service which I want to parse into an Object using Linq.

My goal is to parse the XML into a LIST of <Job> objects - each jobn has a list or <Patch> objects.  My LINQ query is :-

 
var jobs = (from job in xDocument.Descendants("job")
select new Job()
{
	ID	 = int.Parse(job.Attribute("id").Value),
	Location = job.Attribute("address").Value,
	Postcode = job.Attribute("postcode").Value,
	//
	Patches = (from patch in job.Descendants("patch")
		select new Patch()
		{
		ID	= int.Parse(patch.Attribute("id").Value),
		Depth		= decimal.Parse(patch.Attribute("d").Value),
		}).ToList()
}).ToList();

Open in new window


This seemed to work perfectly until I realised that the 'Depth' fiield for a patch can be "" (an empty string.  This causes the query to fall over as it tries to convert an empty string to a decimal.

Is it possible to add more intelligence to the query to check for this?
Avatar of effes
effes
Flag of Germany image

You can try this
Depth		= patch.Attribute("d").Value == string.Empty ? 0 : decimal.Parse(patch.Attribute("d").Value),

Open in new window

This assigns 0 to Depth if patch.Attribute("d").Value is an empty string. Otherwise it will parse the value and assign that to Depth.
Avatar of ChrisMDrew
ChrisMDrew

ASKER

Thanks - I did try something similar but used the C# syntax of putting brackets around the check - doesn't work in LINQ!  I have a similar problem when a field is not specified at all in the XML - for example in the above query sometimes XML is not specified.  Can I check for an attribute being specified in a similar way?  Maybe

Postcode      = job.Attribute("postcode") == null ? ""  job.Attribute("postcode").Value

or is there a better way?
ASKER CERTIFIED SOLUTION
Avatar of effes
effes
Flag of Germany 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