Skip to content

Instantly share code, notes, and snippets.

@jackawatts
Last active August 29, 2024 00:29
Show Gist options
  • Save jackawatts/8b05fe06a41e69bbf37f to your computer and use it in GitHub Desktop.
Save jackawatts/8b05fe06a41e69bbf37f to your computer and use it in GitHub Desktop.
Simple XmlExpando
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Xml.Linq;
namespace Expando
{
public static class XmlExpando
{
public static dynamic Expand(this XDocument xDocument)
{
if (xDocument == null)
throw new ArgumentNullException("xDocument");
if (xDocument.Root == null)
throw new ArgumentException("Document contains no elements", "xDocument");
var xmlExpando = new ExpandoObject();
((IDictionary<string, object>)xmlExpando)[xDocument.Root.Name.LocalName] = new ExpandoObject();
ProcessChildren(((IDictionary<string, object>)xmlExpando)[xDocument.Root.Name.LocalName], xDocument.Root);
return xmlExpando;
}
private static void ProcessChildren(dynamic xmlExpando, XElement xElement)
{
if (xElement.HasAttributes)
{
xmlExpando.Attributes = xElement.Attributes().Select(attribute => new { Name = attribute.Name.LocalName, Value = attribute.Value }).ToDictionary(k => k.Name, v => v.Value);
}
if (xElement.HasElements)
{
var indexableXmlExpando = (IDictionary<string, object>)xmlExpando;
foreach (var childXElement in xElement.Elements())
{
indexableXmlExpando[childXElement.Name.LocalName] = new ExpandoObject();
ProcessChildren(indexableXmlExpando[childXElement.Name.LocalName], childXElement);
}
}
else
{
xmlExpando.Value = xElement.Value;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment