我有以下XML文件,我需要在服务器中将其转换为JSON。最初,我认为我会将其转换为Dictionary,然后使用JavaScriptSerializer将其转换为JSON,但由于每列可能具有不同的值类型,所以我认为它不会起作用。有人在C#/ LINQ中做过类似的事情吗?
我需要保留每列的值类型(布尔,字符串,整数)。
我会很高兴就此提出任何建议,因为我刚刚开始使用XML。谢谢。
<Columns> <Column Name="key1" DataType="Boolean">True</Column> <Column Name="key2" DataType="String">Hello World</Column> <Column Name="key3" DataType="Integer">999</Column> </Columns>
using System; using System.Linq; using System.Web.Script.Serialization; using System.Xml.Linq; class Program { static void Main() { var xml = @"<Columns> <Column Name=""key1"" DataType=""Boolean"">True</Column> <Column Name=""key2"" DataType=""String"">Hello World</Column> <Column Name=""key3"" DataType=""Integer"">999</Column> </Columns>"; var dic = XDocument .Parse(xml) .Descendants("Column") .ToDictionary( c => c.Attribute("Name").Value, c => c.Value ); var json = new JavaScriptSerializer().Serialize(dic); Console.WriteLine(json); } }
产生:
{"key1":"True","key2":"Hello World","key3":"999"}
显然,这会将所有值视为字符串。如果要保留基础类型语义,可以执行以下操作:
using System; using System.Linq; using System.Web.Script.Serialization; using System.Xml.Linq; class Program { static void Main() { var xml = @"<Columns> <Column Name=""key1"" DataType=""System.Boolean"">True</Column> <Column Name=""key2"" DataType=""System.String"">Hello World</Column> <Column Name=""key3"" DataType=""System.Int32"">999</Column> </Columns>"; var dic = XDocument .Parse(xml) .Descendants("Column") .ToDictionary( c => c.Attribute("Name").Value, c => Convert.ChangeType( c.Value, typeof(string).Assembly.GetType(c.Attribute("DataType").Value, true) ) ); var json = new JavaScriptSerializer().Serialize(dic); Console.WriteLine(json); } }
{"key1":true,"key2":"Hello World","key3":999}
而且,如果您不能修改基础XML结构,则需要一个自定义函数,该函数将在您的自定义类型和基础.NET类型之间进行转换:
using System; using System.Linq; using System.Web.Script.Serialization; using System.Xml.Linq; class Program { static void Main() { var xml = @"<Columns> <Column Name=""key1"" DataType=""Boolean"">True</Column> <Column Name=""key2"" DataType=""String"">Hello World</Column> <Column Name=""key3"" DataType=""Integer"">999</Column> </Columns>"; var dic = XDocument .Parse(xml) .Descendants("Column") .ToDictionary( c => c.Attribute("Name").Value, c => Convert.ChangeType( c.Value, GetType(c.Attribute("DataType").Value) ) ); var json = new JavaScriptSerializer().Serialize(dic); Console.WriteLine(json); } private static Type GetType(string type) { switch (type) { case "Integer": return typeof(int); case "String": return typeof(string); case "Boolean": return typeof(bool); // TODO: add any other types that you want to support default: throw new NotSupportedException( string.Format("The type {0} is not supported", type) ); } } }