XmlToDynamic converts your XML object into a hierarchy of nested objects, so you can get at values and attributes more easily.
Instead of this:
xelement.Element(XName.Get("contact")).Attribute(XName.Get("firstName")).Value
You can type this:
xelement.contact["firstName"]
The object returned is also dynamic, so you can add new properties on-the-fly.
To dynamize your XML, simply generate an XElement of it, then call ToDynamic()
on it.
var xmlString = @"<?xml version=""1.0"" encoding=""UTF-8""?><blah></blah>";
var dynamicXml = XElement.Parse(xmlString).ToDynamic();
The elements get converted to properties, and their values can be accessed through the Value
property.
// <addressBook>
// <contacts>
// <contact>
// <name>Jonathan</name>
// </contact>
// </contacts>
// </addressBook>
var firstPersonsName = dynamicXml.contacts[0].name.Value;
// firstPersonsName will be 'Jonathan'
Attributes can be accessed through 'index' syntax, as shown below.
// <addressBook>
// <contacts>
// <contact id="1">
// <name>Jonathan</name>
// </contact>
// </contacts>
// </addressBook>
var firstPersonsId = dynamicXml.contacts[0]["id"];
// firstPersonsId will be '1'
Whenever repeated elements are encountered, they're put into a container which is named after the element names pluralized.
// <colors>
// <blue></blue>
// <green lightness="1"></green>
// <green lightness="10"></green>
// </colors>
var darkGreenLightness = dynamicXml.greens[0]["lightness"];
var lightGreenLightness = dynamicXml.greens[1]["lightness"];
// darkGreenLightness will be '1'
// lightGreenLightness will be '10'