Convert an XML file into BSON

4

I have an Xml Complex that contains "children" nodes and I need to convert it to BSON . I am using VS 2013 (C #).

    
asked by anonymous 28.04.2015 / 21:07

1 answer

2

I think it would be interesting to serialize your XML into a dynamic object first:

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;
    }
  }
}

I took the code from here .

Usage:

var xDoc = XDocument.Load(new StreamReader("seu_xml.xml")); 
dynamic meuObjetoDinamico = new ExpandoObject();
XmlToDynamic.Parse(meuObjetoDinamico, xDoc.Elements().First());

After that, just use the extension method I've taught you to do in this answer .     

29.04.2015 / 17:49