Last active
July 31, 2024 19:27
-
-
Save gfody/d7d450dc54a15e586d5b6ab9794073a4 to your computer and use it in GitHub Desktop.
converts json string to XmlElement, no System.Runtime.Serialization dependency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
else if (m.Groups[1].Value == "{" && name != null) { s.Push(n); n = doc.CreateElement(name); } | |
else if (m.Groups[1].Value == "}" && s.Count > 0) { var p = s.Pop(); p.AppendChild(n); name = n.Name; n = p; } | |
else if ((value = m.Groups[3].Value) != "") | |
{ | |
var x = doc.CreateElement(name ?? unnamed_array_item); | |
if (value.ToLower() != "null") x.AppendChild(doc.CreateTextNode(value.Trim(new char[] { '"' }))); | |
n.AppendChild(x); | |
} | |
m = m.NextMatch(); | |
} | |
return n.FirstChild != null && n.FirstChild.NextSibling == null ? (XmlElement)n.FirstChild : n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
RFC 7159 samples 1 & 2: