Skip to content

Instantly share code, notes, and snippets.

@gfody
gfody / JsonToXml.cs
Last active July 19, 2019 17:29
converts json string to XmlElement, no System.Runtime.Serialization dependency
XmlElement JsonToXml(string json, string root = "root", string unnamed_array_item = "item")
{
var r = new Regex(@"\s*([\[\]{}]|""([^""]*)""\s*:|(true|false|null|-?\d+(?:\.\d+)?|""[^""]*"")\s*),?", RegexOptions.Multiline | RegexOptions.Compiled);
var doc = new XmlDocument(); var n = doc.CreateElement(root); var s = new Stack<XmlElement>(); string name = null, value = "";
var m = r.Match(json);
while (m.Success)
{
if (m.Groups[1].Value == "]") name = null;
else if (m.Groups[1].Value == "[") name = name ?? unnamed_array_item;
else if (m.Groups[1].Value.EndsWith(":")) name = m.Groups[2].Value;