Recently I needed to convert the Json files generated by mongoexport from a MongoDb database to XML so I can analyse the data in Excel. I used Json.NET and the following code to do that.
static XmlNode ConvertToXmlNode(string json, string nodeName)
{
return JsonConvert.DeserializeXmlNode(json, nodeName);
}
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: convert <path> <filename>");
Console.WriteLine("No extensions needed. Uses .json for import and .xml for export");
return;
}
string path = args[0];
string filename = Path.Combine(path, args[1] + ".json");
string dest = Path.Combine(path, args[1] + ".xml");
string nodeName = args[1].ToLower();
Console.WriteLine("Loading " + filename + " and converting to " + dest);
string[] lines = File.ReadAllLines(filename);
Console.WriteLine("Loaded " + lines.Length + " lines");
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
foreach (var line in lines)
{
var imported = doc.ImportNode(ConvertToXmlNode(line, nodeName).FirstChild, true);
root.AppendChild(imported);
}
doc.AppendChild(root);
doc.Save(dest);
Console.WriteLine("Done");
Console.ReadLine();
}