I have the following XML file that I need to convert to JSON in the server. Initially I thought I would convert it to a Dictionary and then use the JavaScriptSerializer to turn it into JSON but since each column could have a different value type, I don't think it would work. Has anyone done something similar before in C#/LINQ?
我有以下XML文件,需要在服务器中转换为JSON。最初我想把它转换成字典,然后使用JavaScriptSerializer将它转换成JSON,但是由于每个列都有不同的值类型,所以我认为它不能工作。有人在c# /LINQ中做过类似的事情吗?
I need to preserve the Value Types(Boolean, String, Integer) of each column.
我需要保存每个列的值类型(布尔型、字符串型、整数型)。
I would appreciate any advice on this as Im just starting to work with XML. Thanks.
如果您对这方面有什么建议,我将非常感激,因为Im刚刚开始使用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>
3 个解决方案
#1
39
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);
}
}
produces:
生产:
{"key1":"True","key2":"Hello World","key3":"999"}
Obviously this treats all the values as strings. If you want to keep the underlying type semantics you could do the following:
显然,这将所有值都视为字符串。如果您想保留底层类型语义,可以执行以下操作:
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);
}
}
produces:
生产:
{"key1":true,"key2":"Hello World","key3":999}
And if you cannot modify the underlying XML structure you will need a custom function that will convert between your custom types and the underlying .NET type:
如果不能修改底层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)
);
}
}
}
#2
25
Is it necessary to use LINQ? Otherwise you can try this:
是否需要使用LINQ?否则你可以试试这个:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
Taken from this post.
从这篇文章。
#3
3
For deep nesting of XML elements with more and unknown attributes you can use this recursion:
对于包含更多和未知属性的XML元素的深度嵌套,可以使用以下递归:
private static string XmlToJson(string xmlString)
{
return new JavaScriptSerializer().Serialize(GetXmlValues(XElement.Parse(xmlString)));
}
private static Dictionary<string, object> GetXmlValues(XElement xml)
{
var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlValues(e)));
else if (!xml.IsEmpty) attr.Add("_value", xml.Value);
return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}
For your example the result will be:
对于你的例子,结果将是:
{
"Columns":{
"_value":[
{
"Column":{
"Name":"key1",
"DataType":"Boolean",
"_value":"True"
}
},
{
"Column":{
"Name":"key2",
"DataType":"String",
"_value":"Hello World"
}
},
{
"Column":{
"Name":"key3",
"DataType":"Integer",
"_value":"999"
}
}
]
}
}
And for more complex XML case like this, you can check the JSON analogue here.
对于像这样复杂的XML,您可以在这里检查JSON类比。
#1
39
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);
}
}
produces:
生产:
{"key1":"True","key2":"Hello World","key3":"999"}
Obviously this treats all the values as strings. If you want to keep the underlying type semantics you could do the following:
显然,这将所有值都视为字符串。如果您想保留底层类型语义,可以执行以下操作:
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);
}
}
produces:
生产:
{"key1":true,"key2":"Hello World","key3":999}
And if you cannot modify the underlying XML structure you will need a custom function that will convert between your custom types and the underlying .NET type:
如果不能修改底层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)
);
}
}
}
#2
25
Is it necessary to use LINQ? Otherwise you can try this:
是否需要使用LINQ?否则你可以试试这个:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
Taken from this post.
从这篇文章。
#3
3
For deep nesting of XML elements with more and unknown attributes you can use this recursion:
对于包含更多和未知属性的XML元素的深度嵌套,可以使用以下递归:
private static string XmlToJson(string xmlString)
{
return new JavaScriptSerializer().Serialize(GetXmlValues(XElement.Parse(xmlString)));
}
private static Dictionary<string, object> GetXmlValues(XElement xml)
{
var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlValues(e)));
else if (!xml.IsEmpty) attr.Add("_value", xml.Value);
return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}
For your example the result will be:
对于你的例子,结果将是:
{
"Columns":{
"_value":[
{
"Column":{
"Name":"key1",
"DataType":"Boolean",
"_value":"True"
}
},
{
"Column":{
"Name":"key2",
"DataType":"String",
"_value":"Hello World"
}
},
{
"Column":{
"Name":"key3",
"DataType":"Integer",
"_value":"999"
}
}
]
}
}
And for more complex XML case like this, you can check the JSON analogue here.
对于像这样复杂的XML,您可以在这里检查JSON类比。