Convert an XML file to BSON

Asked

Viewed 139 times

4

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

  • The title says BSON, but the question speaks in JSON...

  • 1

    The original issue was edited from BSON to JSON by Marconi. I suggested that the title be edited for JSON, before seeing that the question had been edited. I believe the original doubt refers to BSON itself.

  • Personal really my need is Xml for Bson! By dealing with a complex xml (many child nodes) I started with two classes that transform xml into Expandoobject and another that does the reverse path Expandoobject to Xml. I am now searching with transforming from Expandoobject to Bson and vice versa.

  • @Luizrocha Could you check if the answer I provided answers your question? I think here is forgotten.

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.

Use:

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 that I taught to do in this answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.