Search code examples
c#mongodbserializationmongodb-.net-driver

Converting XML to BsonArray in MongoDB using C#


I have an XML file and I want to convert to BsonArray in MongoDB, later then I can make it a list of elements. Here is what I tried.

XmlDocument doc = new XmlDocument();
doc.Load("Books.xml");
string json_doc = JsonConvert.SerializeXmlNode(doc);
...
using (var jsonReader = new JsonReader(json_doc))
{
    var context = BsonDeserializationContext.CreateRoot(jsonReader);
    var document = XML_collection.DocumentSerializer.Deserialize(context);
} 

Code converts XML to Json but not BsonArray. That means what I will get is only ONE document with hundreds of fields. But what I want is making them separate as a list.


Solution

  • You can use BsonDocument.Parse() to read your string and then you can access catalog.book path to cast into BsonArray:

    var json_doc = JsonConvert.SerializeXmlNode(doc);
    var bsonArray = BsonDocument.Parse(json_doc)["catalog"]["book"].AsBsonArray;