Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML to BSON using C#

I want to convert a XML file to BSON. then import the BSON to MongoDB. I searched but could not find how to covert this using C#. please provide me a source code to do this using C#

like image 585
user3535695 Avatar asked Feb 23 '26 09:02

user3535695


1 Answers

Had the same Problem today. It's for sure not the best solution, but i solved it this way in my project and it works for what i need it:

  1. Deserialize XML to Json
  2. Deserialize Json to Bson

    using (var reader = new StreamReader(context.Request.Body))
    {
      var body = reader.ReadToEnd(); // read input string
    
       XmlDocument doc = new XmlDocument();
       doc.LoadXml(body); // String to XML Document
    
       string jsonText = JsonConvert.SerializeXmlNode(doc); //XML to Json
       var bsdocument = BsonSerializer.Deserialize<BsonDocument>(jsonText); //Deserialize JSON String to BSon Document
       var mcollection = Program._database.GetCollection<BsonDocument>("test_collection_05");
       await mcollection.InsertOneAsync(bsdocument); //Insert into mongoDB
     }
    
like image 141
Tom Avatar answered Feb 24 '26 22:02

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!