Advertisement
Guest User

XML to JSON

a guest
Jul 21st, 2016
3,108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.68 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Web.Script.Serialization;
  4. using System.Xml.Linq;
  5.  
  6. class Program
  7. {
  8.     static void Main()
  9.     {
  10.         var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse("<xml/>")));
  11.     }
  12.  
  13.     private static Dictionary<string, object> GetXmlData(XElement xml)
  14.     {
  15.         var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
  16.         if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
  17.         else if (!xml.IsEmpty) attr.Add("_value", xml.Value);
  18.  
  19.         return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
  20.     }
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement