使用C#将XML转换为BSON

3

我想将一个XML文件转换成BSON格式,然后导入到MongoDB。我搜索了一下,但是找不到用C#来实现这个转换的方法。请提供一份用C#实现这个转换的源代码。


请查看此处的被接受的答案(https://dev59.com/1HbZa4cB1Zd3GeqPGHQG),同时参考[c#中的XML转JSON](https://dev59.com/pmct5IYBdhLWcg3whtqh)。 - Nilay Vishwakarma
将您的XML反序列化为C#对象。然后,使用MongoDb驱动程序将该对象序列化为集合。最简单的方法是向C#类添加属性以控制序列化过程。如果尝试后仍无法正常工作,请发布更多详细信息,以便我们能够更好地帮助您。 - WiredPrairie
1个回答

4

今天我遇到了同样的问题。虽然这不是最好的解决办法,但是我在我的项目中使用了这种方式解决了问题,并且它对我所需的内容有效:

  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
     }
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接