環境VS2010 .net 4.0


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Xml;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String sss = "{ \"firstName\": \"John\", \"lastName\": \"Smith\", \"sex\": \"third\", \"age\": 25, \"address\": { \"streetAddress\": \"21 2nd Street\", \"city\": \"New York\", \"state\": \"NY\", \"postalCode\": \"10021\" }, \"phoneNumber\": [ { \"type\": \"home\", \"number\": \"212 555-1234\" }, { \"type\": \"fax\", \"number\": \"646 555-4567\" } ] }";
XmlDocument testc= JsonToXml(sss);
}
public static XmlDocument JsonToXml(string sJson)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var dic = (Dictionary<string, object>)serializer.DeserializeObject(sJson);
var doc = new XmlDocument();
XmlDeclaration xmlDec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.InsertBefore(xmlDec, doc.DocumentElement);
XmlElement root = doc.CreateElement("Invoice");
doc.AppendChild(root);
foreach (var item in dic)
{
XmlElement element = doc.CreateElement(item.Key);
KeyValue2Xml(element, item);
root.AppendChild(element);
}
return doc;
}
private static void KeyValue2Xml(XmlElement node, KeyValuePair<string, object> source)
{
object kValue = source.Value;
if (kValue.GetType() == typeof(Dictionary<string, object>))
{
var dictionary = kValue as Dictionary<string, object>;
if (dictionary != null)
foreach (var item in dictionary)
{
if (node.OwnerDocument != null)
{
XmlElement element = node.OwnerDocument.CreateElement(item.Key);
KeyValue2Xml(element, item);
node.AppendChild(element);
}
}
}
else if (kValue.GetType() == typeof(object[]))
{
var o = kValue as object[];
if (o != null)
foreach (object t in o)
{
if (node.OwnerDocument != null)
{
XmlElement xitem = node.OwnerDocument.CreateElement("Item");
var item = new KeyValuePair<string, object>("Item", t);
KeyValue2Xml(xitem, item);
node.AppendChild(xitem);
}
}
}
else
{
if (node.OwnerDocument != null)
{
XmlText text = node.OwnerDocument.CreateTextNode(kValue.ToString());
node.AppendChild(text);
}
}
}
}
}



參考:
http://www.cnblogs.com/shenzhoulong/archive/2011/01/27/1946532.html
http://www.verydemo.com/demo_c230_i126217.html
http://blog.csdn.net/jiankunking/article/details/17992703



arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()