Skip to content

Instantly share code, notes, and snippets.

@iSynaptic
Created December 2, 2013 21:04
Show Gist options
  • Save iSynaptic/7758940 to your computer and use it in GitHub Desktop.
Save iSynaptic/7758940 to your computer and use it in GitHub Desktop.
Convert from Xml to JSON
private static JToken ConvertFromXml(XElement element)
{
if (!element.HasAttributes && !element.HasElements)
return new JValue(element.Value);
var attributes = element.Attributes()
.Select(x => new JProperty(NormalizeName(x.Name.LocalName), x.Value));
var elements = element.Elements()
.GroupBy(x => x.Name.LocalName)
.Select(x => new { Name = x.Key, Elements = x.ToArray() })
.Select(x => new JProperty(NormalizeName(x.Name), x.Elements.Length > 1
? new JArray(x.Elements.Select(ConvertFromXml).Cast<object>().ToArray())
: ConvertFromXml(x.Elements[0])));
var content = attributes.Concat(elements);
var textNodes = element.Nodes()
.Where(x => x.NodeType == XmlNodeType.Text)
.Cast<XText>()
.ToArray();
if (!element.HasElements && textNodes.Length == 1)
{
content = content.Concat(new[] {new JProperty("#value", textNodes[0].Value)});
}
else if (textNodes.Any())
{
var prop = new JProperty("#text", textNodes.Length > 1
? (JToken)new JArray(textNodes.Select(x => new JValue(x.Value)))
: new JValue(textNodes[0].Value)
);
content = content.Concat(new[] { prop });
}
return new JObject(content.OfType<object>().ToArray());
}
private static readonly Regex _NormalizeRegex = new Regex("[._]+", RegexOptions.Compiled);
private static string NormalizeName(string input)
{
if (input.Length <= 1) return input;
return _NormalizeRegex.Replace(input, "-");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment