Kash Farooq's software development blog

.NET Developer

Creating dynamic objects from XML in .NET 4

Posted by Kash Farooq on July 1, 2013

After looking at using dynamics to create objects from JSON in .NET 4, I wondered if you can do the same with XML.

I couldn’t find anything straight out of the box, but I did find this excellent sample code: Dynamic XML Reader with C# and .Net 4.0.

Here is a quick demonstration of what you can do with it.

With the following XML:

<quartzJobs>
 <job type="HelloWorld.HelloJob,HelloWorld" cronSchedule="0/5 * * * * ?" />
 <job type="HelloWorld2.HelloJob2,HelloWorld2" cronSchedule="0/7 * * * * ?" />
</quartzJobs>

You can do this:

dynamic jobConfig = new DynamicXml(File.ReadAllText("Jobs.XML"));
foreach (var job in jobConfig.job)
{
  Console.WriteLine(string.Format("Job to run: {0}. Schedule: {1}", job.type, job.cronSchedule));
}

Very nice. I reckon it is a lot less clunky than LINQ to XML.

Advertisements

Sorry, the comment form is closed at this time.

 
%d bloggers like this: