Parse XML to dynamic object in C#

<?xml version="1.0" encoding="utf-8" ?>
<contacts>
  <contact id='1'>
    <firstName>Michael</firstName>
    <lastName>Jordan</lastName>
    <age>40</age>
    <dob>1965</dob>
    <salary>100.35</salary>
  </contact>
  <contact id='2'>
    <firstName>Scottie</firstName>
    <lastName>Pippen</lastName>
    <age>38</age>
    <dob>1967</dob>
    <salary>55.28</salary>
  </contact>
</contacts>
public class XmlToDynamic
{
  public static void Parse(dynamic parent, XElement node)
  {
    if (node.HasElements)
    {
      if (node.Elements(node.Elements().First().Name.LocalName).Count() > 1)
      {
        //list
        var item = new ExpandoObject();
        var list = new List<dynamic>();
        foreach (var element in node.Elements())
        {            
          Parse(list, element);            
        }
 
        AddProperty(item, node.Elements().First().Name.LocalName, list);
        AddProperty(parent, node.Name.ToString(), item);
      }
      else
      {
        var item = new ExpandoObject();
 
        foreach (var attribute in node.Attributes())
        {
          AddProperty(item, attribute.Name.ToString(), attribute.Value.Trim());
        }
 
        //element
        foreach (var element in node.Elements())
        {
          Parse(item, element);
        }
 
        AddProperty(parent, node.Name.ToString(), item);
      }
    }
    else
    {
      AddProperty(parent, node.Name.ToString(), node.Value.Trim());
    }
  }
 
  private static void AddProperty(dynamic parent, string name, object value)
  {
    if (parent is List<dynamic>)
    {
      (parent as List<dynamic>).Add(value);
    }
    else
    {
      (parent as IDictionary<String, object>)[name] = value;
    }
  }
}
[Test]
public void Test()
{
  //read from text
  //var xDoc = XDocument.Parse(txt);
 
  //read from url
  //var request = WebRequest.Create(@"http://...") as HttpWebRequest;
  //request.Credentials = CredentialCache.DefaultNetworkCredentials;
  //var xDoc = XDocument.Load(request.GetResponse().GetResponseStream());
 
  //read from file
  var xDoc = XDocument.Load(new StreamReader("contacts.xml"));
 
  dynamic root = new ExpandoObject();
 
  XmlToDynamic.Parse(root, xDoc.Elements().First());
 
  Console.WriteLine(root.contacts.contact.Count);
  Console.WriteLine(root.contacts.contact[0].firstName);
  Console.WriteLine(root.contacts.contact[0].id);
}

Comments

  1. This is the most functional XML to dynamic ExpandoObject code I've seen yet. That said, it does make assumptions that all XML looks like the test XML. (All examples I've seen so far assume all XML looks like their sample XML, though.) For example, in the Parse method:

    (node.Elements(node.Elements().First().Name.LocalName).Count() > 1)

    The above line assumes that if the first child element is not a list, the remainder of the elements are not lists either. It is completely possible that there is a series of non-list attributes followed by one or more lists (as in the XML I am required to consume from a third party.)

    ReplyDelete
  2. A Code Project article updating this code has been posted to the following URL:

    http://www.codeproject.com/Articles/461677/Creating-a-dynamic-object-from-XML-using-ExpandoOb

    ReplyDelete
  3. An Alternative:

    public static dynamic Convert(XElement parent)
    {
    dynamic output = new ExpandoObject();

    output.Name = parent.Name.LocalName;
    output.Value = parent.Value;

    output.HasAttributes = parent.HasAttributes;
    if (parent.HasAttributes)
    {
    output.Attributes = new List>();
    foreach (XAttribute attr in parent.Attributes())
    {
    KeyValuePair temp = new KeyValuePair(attr.Name.LocalName, attr.Value);
    output.Attributes.Add(temp);
    }
    }

    output.HasElements = parent.HasElements;
    if (parent.HasElements)
    {
    output.Children = new List();
    foreach (XElement element in parent.Elements())
    {
    dynamic temp = Convert(element);
    output.Elements.Add(temp);
    }
    }

    return output;
    }

    ReplyDelete
  4. It's very useful blog post with informative and insightful content and i had good experience with this information.I have gone through CRS Info Solutions Home which really nice. Learn more details About Us of CRS info solutions. Here you can see the Courses CRS Info Solutions full list. Find Student Registration page and register now. Go through Blog post of crs info solutions. I just read these Reviews of crs really great. You can now Contact Us of crs info solutions. You enroll for Pega Training at crs info solutions.

    ReplyDelete
  5. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.izmir istanbul ucak biletleri

    ReplyDelete
  6. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.turk hava yollari

    ReplyDelete
  7. Great Article IoT Projects for Students

    Deep Learning Projects for Final Year

    JavaScript Training in Chennai

    JavaScript Training in Chennai

    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete
  8. อีกทั้งเรายังให้บริการ เกมสล็อต ยิงปลา แทงบอลออนไลน์ รองรับทุกการใช้งานในอุปกรณ์ต่าง ๆ HTML5 คอมพิวเตอร์ แท็บเล็ต สมาทโฟน คาสิโนออนไลน์ และมือถือทุกรุ่น เล่นได้ตลอด 24ชม. ไม่ต้อง Downloads เกมส์ให้ยุ่งยาก ด้วยระบบที่เสถียรที่สุดในประเทศไทย

    ReplyDelete
  9. Online slots (Slot Online) is the release of a gambling piece of equipment. Slot computer As pointed out Used create electrical games known as web-based slots, as a result of the development era, folks have turned to gamble through computer systems. Will achieve slot games making online gambling games Via the world wide web network device Which players can play throughout the slot plan or will play Slots through the service provider's website Which online slots games are actually on hand around the form of playing policies. It is similar to playing on a slot piece of equipment. Both realistic images as well as audio are likewise thrilling as they go to living room in the casino in the world.บาคาร่า
    ufa
    ufabet
    แทงบอล
    แทงบอล
    แทงบอล

    ReplyDelete
  10. pgslot ซึ่งเกมคาสิโนออนไลน์เกมนี้เป็นเกมที่เรียกว่าเกม สล็อตเอ็กซ์โอ คุณรู้จักเกมส์เอ็กซ์โอหรือไม่ 90% ต้องรู้จักเกมส์เอ็กซ์โออย่างแน่นอนเพราะในตอนนี้เด็กนั้นเราทุกคนมักที่จะเอาก็ได้ขึ้นมา สล็อต เล่นเกมส์เอ็กซ์โอกับเพื่อนเพื่อนแล้วคุณรู้หรือไม่ว่าในปัจจุบันนี้เกมส์เอ็กซ์โอนั้นกลายมาเป็นเกมซะลอสออนไลน์ที่ให้บริการด้วยเว็บคาสิโนออนไลน์คุณสามารถเดิมพันเกมส์เอ็กซ์โอกับเว็บคาสิโนออนไลน์ได้โดยที่จะทำให้คุณนั้นสามารถสร้างกำไรจากการเล่นเกมส์เดิมพันออนไลน์ได้เราแนะนำเกมส์ชนิดนี้ให้คุณได้รู้จักก็เพราะว่าเชื่อว่าทุก

    ReplyDelete
  11. London and the entire top security companies in London
    UK isn't safe for those who are rich. There are criminal gangs who are always planning on who to pounce on next.

    ReplyDelete

Post a Comment

Popular posts from this blog

Parse XML to object model in C# using XSD utility