Parse XML to Dynamic ExpandoObject C# .NET 4.0

The example below uses the LINQ to XML predecessor System.Xml.XmlDocument simply because I still prefer the regex parsing method. It can easily be adapted to use XDocument instead based on your preference. The end resulting output (IEnumerable) is the same.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Dynamic;
using System.Xml.Linq;

namespace AIS.Common
    public class DocParser : IDisposable
        public enum DocTypes

        private XmlDocument Document { get; set; }
        //private XDocument Document { get; set; }
        private DocTypes DocType { get; set; }

        /// <summary>
        /// </summary>
        /// <param name="dt">type of document, currently only supports xml</param>
        /// <param name="f">filename and path</param>
        public DocParser(DocTypes dt, string fp)
                switch (dt)
                    case DocTypes.Xml:
                        DocType = DocTypes.Xml;

                        Document = new XmlDocument();

                        //Document = XDocument.Load(fp);
                        throw new Exception("Constructor::invalid or unknown doc type specified");
            catch (Exception ex)
                throw new Exception("Constructor::Error with document load or doc type.",ex);

        public IEnumerable<dynamic> GetElements(string regex)
            return XmlToExpandoObject(regex);

        private IEnumerable<dynamic> XmlToExpandoObject(string regex)
            dynamic eo = new ExpandoObject();
            var dictionary = eo as IDictionary<string, object>;
            XmlNodeList xnl = Document.SelectNodes(regex);
            foreach (XmlNode xn in xnl)
                foreach (XmlAttribute xa in xn.Attributes)
                    dictionary[xa.Name.ToString()] = xa.Value.Trim();
                    //TrySetAttr(xn.LocalName, xn);

                yield return eo;

sample xml:

<?xml version="1.0" encoding="utf-8" ?>
  <robot id="1" age="5" />
  <robot id="2" age="3" />


DocParser dp = new DocParser(DocParser.DocTypes.Xml, Server.MapPath("~/xmlfilename.xml")); //can also retrieve xml from external service, etc
        var robots = dp.GetElements("*/robot");
foreach (var r in robots) {
Console.WriteLine("Robot id={0}, age={1}",,r.age); //output. if this is web app you will likely do this differently



About Ronnie Diaz

Ronnie Diaz is a software engineer and tech consultant. Ronnie started his career in front-end and back-end development for companies in ecommerce, service industries and remote education. This work transitioned from traditional desktop client-server applications through early cloud development. Software included human resource management and service technician workflows, online retail e-commerce and electronic ordering and fulfillment, IVR customer relational systems, and video streaming remote learning SCORM web applications. Hands on server experience and software performance optimization led to creation of a startup business focused on collocated data center services and continued experience with video streaming hardware and software. This led to a career in Amazon Prime Video where Ronnie is currently employed, building software and systems which stream live sports and events for millions of viewers around the world.

Posted on August 23, 2013, in Programming & Development and tagged , , , , , , , , , , . Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: