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) ); } }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)