2

Consider I have an XML file which is loaded into an XElement or something like it. One way of reaching the tag values is to use Element() method.

Is there any way to facilitate this using dynamic objects. For example I want to replace

var val = xelement.Element("Name").Value

with

var dyn = (dynamic)xelement;
var val = dyn.Name;

It's a good idea to have nested properties too. For example:

var val = dyn.Person.Name;

Or even better:

var val = dyn.Children.Where(c=>c.Name == "Mehran").FirstOrDefault().Age;

1 Answer 1

2

I believe I've answered your question in the form of a blog post which you can read at http://blog.waseem-sabjee.com/2014/09/14/how-to-convert-an-xml-document-to-a-dynamic-object-in-net/

the blog post also contains a download link to a working solution.

here's some implementation code for you to look at: (note that the ToDynamicList method is an extension method, the code for it is available on my blog.)

            XElement doc = XElement.Load(reader);

            // using our ToDynamicList (Extenion Method)
            var people = doc.ToDynamicList();

            // loop through each person
            foreach (dynamic person in people.Where(X => X.Name == "Waseem"))
            {
                Console.WriteLine("id:\t" + person.Id);
                Console.WriteLine("Name:\t" + person.Name);
                Console.WriteLine("Age:\t" + person.Age);
                Console.WriteLine("----------------------------------");
                try
                {
                    // loop through children, if any
                    foreach(dynamic child in person.Children)
                    {
                        Console.WriteLine("\tid:\t" + child.Id);
                        Console.WriteLine("\tName:\t" + child.Name);
                        Console.WriteLine("\tAge:\t" + child.Age);
                    }
                    Console.WriteLine("----------------------------------");
                }
                catch(Exception ex)
                {
                }
            }

        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.