2014-04-16 47 views
3

我想將XML文件轉換爲BSON。然後將BSON導入MongoDB。我搜索,但無法找到如何使用C#隱藏這個。請爲我提供一個使用C#編寫的源代碼。使用C#將XML轉換爲BSON#

+0

請參閱接受的答案[這裏](http://stackoverflow.com/questions/18611773/dynamic-xml-into-mongodb),也請參考[在C#中XML到JSON](http:// stackoverflow。 com/questions/12037085/convert-xml-to-json-using-c-linq) –

+0

將您的XML反序列化爲一個c#對象。然後,使用MongoDb驅動程序將該對象序列化爲集合。最簡單的是添加屬性到C#類來控制序列化過程。在您嘗試之後,如果它不起作用,請發佈更多細節,以便我們能夠更好地提供幫助。 – WiredPrairie

回答

2

今天有同樣的問題。 這肯定不是最好的解決辦法,但 我解決它在我的項目這種方式,它適用於什麼我需要它:

  1. 反序列化XML到JSON
  2. 反序列化JSON來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 
    }