Skip to content

Instantly share code, notes, and snippets.

@serbrech
Forked from asoftwareguy/XmlExpandoObject.cs
Last active December 16, 2015 04:29
Show Gist options
  • Save serbrech/5378005 to your computer and use it in GitHub Desktop.
Save serbrech/5378005 to your computer and use it in GitHub Desktop.

Transform an xml string into a dynamic object

It gives a nice syntax to read an xml string. the value of the nodes end up in the value property.
Attributes are treated like nodes (so careful, you could miss data if an attribute has the same name as a node...).
The attribute values end up under the value property as well.
Since an example is always better than an explaination, see Example.cs.

using Xunit;
namespace Test
{
public class Tests
{
[Fact]
public void XmlReaderTest()
{
string example =
@"<root>
<expando>
<method name=""GetExpando"">I parse catz</method>
<result>poneyz</result>
</expando>
</root>";
var xml = XmlExpandoObject.GetExpando(example);
Assert.Equal("GetExpando", xml.root.expando.method.name.value);
Assert.Equal("I parse catz", xml.root.expando.method.value);
Assert.Equal("poneyz", xml.root.expando.result.value);
}
}
}
using System;
using System.Dynamic;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
namespace Test
{
public static class XmlExpandoObject
{
public static dynamic GetExpando(string xmlFile)
{
var doc = XDocument.Parse(xmlFile);
return GetExpandoForNodes(doc.Elements());
}
private static dynamic GetExpandoForNodes(IEnumerable<XElement> elements)
{
dynamic result = new ExpandoObject();
foreach (var n in elements)
{
if (!n.Elements().Any())
{
((IDictionary<String, object>)result)[n.Name.LocalName] = new ExpandoObject();
dynamic node = ((IDictionary<String, object>)result)[n.Name.LocalName];
node.value = n.Value.Trim();
}
else
{
dynamic child = GetExpandoForNodes(n.Elements());
(result as IDictionary<String, object>)[n.Name.LocalName] = child;
}
//Adds attributes as properties on the node
foreach (var att in n.Attributes())
{
var node = ((IDictionary<String, object>) result)[n.Name.LocalName] ?? new ExpandoObject();
((IDictionary<String, object>) node)[att.Name.LocalName] = new ExpandoObject();
dynamic attribute = ((IDictionary<String, object>) node)[att.Name.LocalName];
attribute.value = att.Value.Trim();
}
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment