Skip to content

Instantly share code, notes, and snippets.

@mgroves
Created July 5, 2017 15:49
Show Gist options
  • Save mgroves/59f504a3dc4e04cc261dd35ac0a70d27 to your computer and use it in GitHub Desktop.
Save mgroves/59f504a3dc4e04cc261dd35ac0a70d27 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Xml;
using Couchbase;
using Couchbase.Configuration.Client;
using Newtonsoft.Json;
using Formatting = Newtonsoft.Json.Formatting;
namespace LoadingXml
{
// http://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm
// http://www.newtonsoft.com/json/help/html/Introduction.htm
class Program
{
static void Main(string[] args)
{
// sample XML, parsed into an XmlDocument
// this might come from an XML file, another database, a REST API, etc
// but for this example, it's just a hardcoded string
var xml = @"
<Invoice>
<Timestamp>1/1/2017 00:01</Timestamp>
<CustNumber>12345</CustNumber>
<AcctNumber>54321</AcctNumber>
</Invoice>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
// convert XML into JSON using Newtonsoft Json.net
var json = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);
// connect to couchbase cluster
ClusterHelper.Initialize(new ClientConfiguration
{
Servers = new List<Uri> {new Uri("http://localhost:8091")}
});
var bucket = ClusterHelper.GetBucket("loadxml", "password");
// insert directly (literal translation)
object transactObject1 = JsonConvert.DeserializeObject(json);
bucket.Insert(Guid.NewGuid().ToString(), transactObject1);
// insert via class (type information, naming conventions applied)
Invoice transactObject2 = JsonConvert.DeserializeObject<Invoice>(json);
bucket.Insert(Guid.NewGuid().ToString(), transactObject2);
}
}
public class Invoice
{
public DateTime Timestamp { get; set; }
public string CustNumber { get; set; }
public int AcctNumber { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment