JSON格式转换成XML格式

第一种方法:

需要使用命名空间System.Runtime.Serialization.Json

下面有JsonReaderWriterFactory

XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(sJson), XmlDictionaryReaderQuotas.Max);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
 

 

使用组件:System.Web.Extensions

类全称:System.Web.Script.Serialization.JavaScriptSerializer

要先引用 System.Web.Extensions

需要使用的命名空间   System.Web.Script.Serialization.JavaScriptSerializer

下面有JavaScriptSerializer

// json字符串转换为Xml对象
public static XmlDocument Json2Xml(string sJson)
{
            //XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(sJson), XmlDictionaryReaderQuotas.Max);
            //XmlDocument doc = new XmlDocument();
            //doc.Load(reader); 

            JavaScriptSerializer oSerializer = new JavaScriptSerializer();
            Dictionary Dic = (Dictionary)oSerializer.DeserializeObject(sJson);
            XmlDocument doc = new XmlDocument();
            XmlDeclaration xmlDec;
            xmlDec = doc.CreateXmlDeclaration("1.0", "gb2312", "yes");
            doc.InsertBefore(xmlDec, doc.DocumentElement);
            XmlElement nRoot = doc.createElement_x("root");
            doc.AppendChild(nRoot);
            foreach (KeyValuePair item in Dic)
           {
                XmlElement element = doc.createElement_x(item.Key);
                KeyValue2Xml(element, item);
                nRoot.AppendChild(element);
           }
            return doc;

private static void KeyValue2Xml(XmlElement node, KeyValuePair Source)
{
          object kValue = Source.Value;
           if (kValue.GetType() == typeof(Dictionary))
          {
              foreach (KeyValuePair item in kValue as Dictionary)
              {
                   XmlElement element = node.OwnerDocument.createElement_x(item.Key);
                   KeyValue2Xml(element, item);
                   node.AppendChild(element);
              }
          }
          else if (kValue.GetType() == typeof(object[]))
          {
             object[] o = kValue as object[];
             for (int i = 0; i < o.Length; i++)
                {
                     XmlElement xitem = node.OwnerDocument.createElement_x("Item");
                     KeyValuePair item = new KeyValuePair("Item", o[i]);
                     KeyValue2Xml(xitem, item);
                     node.AppendChild(xitem);
                }

           }
           else
           {
                XmlText text = node.OwnerDocument.CreateTextNode(kValue.ToString());
                node.AppendChild(text);
           }

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Windows.Forms;
using System.Runtime.Serialization.Json;
using System.Collections;
//using Open_Newtonsoft_Json;

namespace WeChatTool
{
public static class xmlHelper
{
//XmlTextWriter
public static void ss()
{
String filename = String.Concat("test3.xml");
using (StreamWriter sw = new StreamWriter(filename))
{
// Create Xml Writer.
XmlTextWriter xmlWriter = new XmlTextWriter(sw);
// 也可以使用public XmlTextWriter(string filename, Encoding encoding)来构造
// encoding默认为 UTF-8.
//XmlTextWriter writer = new XmlTextWriter("test3.xml", null);
// Set indenting so that its easier to read XML when open in Notepad and such apps.
xmlWriter.Formatting = Formatting.Indented;
// This will output the XML declaration
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Contacts");
xmlWriter.WriteStartElement("Contact");
xmlWriter.WriteAttributeString("id", "01");
xmlWriter.WriteElementString("Name", "Daisy Abbey");
xmlWriter.WriteElementString("Gender", "female");
// close contact
xmlWriter.WriteEndElement();
// close contacts
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
}

//LINQ to XML 的XDocument
public static void xx()
{
//var doc = new XDocument(new XElement("Contacts",
// new XElement("Contact", new XAttribute("id", "01"),
// new XElement("Name", "Daisy Abbey"),
// new XElement("Gender", "female"))));
//doc.Save("test2.xml");
}

//XmlDocument 写入
public static void XmlDocumentWriter(string userName, string appid, string appsecret, DateTime appdate)
{
#region MyRegion
try
{
string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
//if (File.Exists(xmlPath)==false string.IsNullOrEmpty(xmlPath) || xmlPath == "")
if (File.Exists(xmlPath) == false)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null));
var root = xmlDoc.CreateElement("config");
xmlDoc.AppendChild(root);
// User UserInfo
XmlElement elementUser = xmlDoc.CreateElement("dev");
//elementUser.InnerText = userName;
root.AppendChild(elementUser);

XmlElement elementName = xmlDoc.CreateElement("Name");
elementName.InnerText = userName;
elementUser.AppendChild(elementName);

XmlElement elementAppid = xmlDoc.CreateElement("Appid");
elementAppid.InnerText = appid;
//XmlAttribute attrID = xmlDoc.CreateAttribute("id");
//attrID.Value = "01";
//elementAppid.Attributes.Append(attrID);
elementUser.AppendChild(elementAppid);

XmlElement elementAppsecret = xmlDoc.CreateElement("Appsecret");
elementAppsecret.InnerText = appsecret;
elementUser.AppendChild(elementAppsecret);

//XmlElement elementDate = xmlDoc.CreateElement("AppDate");
//elementDate.InnerText = appdate.ToLocalTime().ToString();
//elementUser.AppendChild(elementDate);

xmlDoc.Save("config.xml");
MessageBox.Show("用户信息保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
//XmlNode node = doc.SelectSingleNode("/Users/UserInfo/Name");
XmlNodeList nodes = xmlDoc.SelectNodes("/config/dev");
if (nodes.Count > 0)
{
// User
XmlNode root = xmlDoc.SelectSingleNode("/config");

XmlElement elementUser = xmlDoc.CreateElement("dev");
//elementUser.InnerText = userName;
root.AppendChild(elementUser);

XmlElement elementName = xmlDoc.CreateElement("Name");
elementName.InnerText = userName;
elementUser.AppendChild(elementName);

XmlElement elementAppid = xmlDoc.CreateElement("Appid");
elementAppid.InnerText = appid;
//XmlAttribute attrID = xmlDoc.CreateAttribute("id");
//attrID.Value = "01";
//elementAppid.Attributes.Append(attrID);
elementUser.AppendChild(elementAppid);

XmlElement elementAppsecret = xmlDoc.CreateElement("Appsecret");
elementAppsecret.InnerText = appsecret;
elementUser.AppendChild(elementAppsecret);

//XmlElement elementDate = xmlDoc.CreateElement("AppDate");
//elementDate.InnerText = appdate.ToLocalTime().ToString();
//elementUser.AppendChild(elementDate);

xmlDoc.Save("config.xml");
MessageBox.Show("用户信息保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show("用户信息保存有问题! " + ex.ToString(), "提示信息!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
//throw;
}
#endregion
}

//XmlDocument11 读取
public static Queue XmlDocumentQuery()
{
Queue queue = new Queue();
string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
if (string.IsNullOrWhiteSpace(xmlPath) || xmlPath == null)
{
return queue;
}
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
//根据要查询的字段进行查询,遍历使用的是xpath
XmlNodeList nodes = doc.SelectNodes("/config/dev");
foreach (XmlNode xmlnode in nodes)
{
if (xmlnode.HasChildNodes)
{
if (xmlnode.ChildNodes.Count > 2)
{
FrmUser user = new FrmUser();
user.UserName = xmlnode.ChildNodes[0].InnerText;
user.Appid = xmlnode.ChildNodes[1].InnerText;
user.Appsecret = xmlnode.ChildNodes[2].InnerText;
queue.Enqueue(user);
}
else if (xmlnode.ChildNodes.Count > 1)
{
FrmUser user = new FrmUser();
user.UserName = xmlnode.ChildNodes[0].InnerText;
user.Appid = xmlnode.ChildNodes[1].InnerText;
//user.Appsecret = xmlnode.ChildNodes[2].InnerText;
queue.Enqueue(user);
}
else if (xmlnode.ChildNodes.Count > 0)
{
FrmUser user = new FrmUser();
user.UserName = xmlnode.ChildNodes[0].InnerText;
//user.Appid = xmlnode.ChildNodes[1].InnerText;
//user.Appsecret = xmlnode.ChildNodes[2].InnerText;
queue.Enqueue(user);
}
}
}
return queue;
}

//XmlDocument 读取
public static XmlNode XmlDocumentQuery(string userName, string appid, string appsecret, DateTime appdate)
{
string xmlPath = System.IO.Path.Combine(Application.StartupPath, "UserInfo.xml");
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
//根据要查询的字段进行查询,遍历使用的是xpath
string xx = userName;
DateTime xx1 = appdate;
//XmlNode node = doc.SelectSingleNode("/UserInfo/"+comboBox1.SelectedItem);
XmlNodeList nodes = doc.SelectNodes("/Users/UserInfo");
foreach (XmlNode xmlnode in nodes)
{
if (xmlnode.HasChildNodes)
{
foreach (XmlNode xmlSubNode in xmlnode.ChildNodes)
{
if (xmlSubNode.InnerText == xx)
{
//this.richTextBox3.AppendText("用户信息:");
foreach (XmlNode SubNode in xmlnode.ChildNodes)
{
return SubNode;
//this.richTextBox3.AppendText(Environment.NewLine + " " + SubNode.Name + ":" + SubNode.InnerText);
}
//return;
}
}
}
}
return null;
}

//XmlDocument 修改
public static void XmlDocumentModified(FrmUser oldUser, FrmUser newuUser, DateTime appdate)
{
string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
//根据要查询的字段进行查询,遍历使用的是xpath
//XmlNode node = doc.SelectSingleNode("/UserInfo/"+comboBox1.SelectedItem);
XmlNodeList nodes = doc.SelectNodes("/config/dev");
foreach (XmlNode xmlnode in nodes)
{
if (xmlnode.HasChildNodes)
{
if (xmlnode.ChildNodes.Count > 2)
{
if (xmlnode.ChildNodes[0].InnerText == oldUser.UserName
&& xmlnode.ChildNodes[1].InnerText == oldUser.Appid
&& xmlnode.ChildNodes[2].InnerText == oldUser.Appsecret)
{
xmlnode.ChildNodes[0].InnerText = newuUser.UserName;
xmlnode.ChildNodes[1].InnerText = newuUser.Appid;
xmlnode.ChildNodes[2].InnerText = newuUser.Appsecret;
}
}
else if (xmlnode.ChildNodes.Count > 1)
{
if (xmlnode.ChildNodes[0].InnerText == oldUser.UserName
&& xmlnode.ChildNodes[1].InnerText == oldUser.Appid)
{
xmlnode.ChildNodes[0].InnerText = newuUser.UserName;
xmlnode.ChildNodes[1].InnerText = newuUser.Appid;
}
}
else if (xmlnode.ChildNodes.Count > 0)
{
if (xmlnode.ChildNodes[0].InnerText == oldUser.UserName)
{
xmlnode.ChildNodes[0].InnerText = newuUser.UserName;
}
}

}
}
doc.Save("config.xml");
MessageBox.Show("用户信息修改保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

//XmlDocument 删除
public static void XmlDocumentDelete(FrmUser user, DateTime appdate)
{
string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
//根据要查询的字段进行查询,遍历使用的是xpath
//XmlNode node = doc.SelectSingleNode("/UserInfo/"+comboBox1.SelectedItem);
XmlNodeList nodes = doc.SelectNodes("/config/dev");
foreach (XmlNode xmlnode in nodes)
{
if (xmlnode.HasChildNodes)
{
if (xmlnode.ChildNodes.Count > 2)
{
if (xmlnode.ChildNodes[0].InnerText == user.UserName
&& xmlnode.ChildNodes[1].InnerText == user.Appid
&& xmlnode.ChildNodes[2].InnerText == user.Appsecret)
{
XmlNode parentNode = xmlnode.ParentNode;
parentNode.RemoveChild(xmlnode);
}
}
else if (xmlnode.ChildNodes.Count > 1)
{
if (xmlnode.ChildNodes[0].InnerText == user.UserName
&& xmlnode.ChildNodes[1].InnerText == user.Appid)
{
XmlNode parentNode = xmlnode.ParentNode;
parentNode.RemoveChild(xmlnode);
}
}
else if (xmlnode.ChildNodes.Count > 0)
{
if (xmlnode.ChildNodes[0].InnerText == user.UserName)
{
XmlNode parentNode = xmlnode.ParentNode;
parentNode.RemoveChild(xmlnode);
}
}

}
}
doc.Save("config.xml");
MessageBox.Show("用户信息删除保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}


public static XmlDocument JsonToXml(string json)
{
XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
return doc;
}
// 从一个对象信息生成Json串
public static string ObjectToJson(object obj)
{
string json = null;
//StringBuilder sb = new StringBuilder();
//JsonSerializer serialize = new JsonSerializer();
//serialize.Serialize
DataContractJsonSerializer serialize = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serialize.WriteObject(ms, obj);
byte[] readbyte = new byte[ms.Length];
ms.Read(readbyte, 0, (int)ms.Length);
json = Encoding.UTF8.GetString(readbyte);
return json;
}
// 从一个Json串生成对象信息
public static object JsonToObject(string jsonString, object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
return serializer.ReadObject(mStream);
}

}
}

第二种方法:

XML TO JSON  

string xml = @"

  
   Alan
   http://www.google.com
  
  
   Louis
   http://www.yahoo.com
  
" ;

 

XmlDocument doc =  new  XmlDocument();
doc.LoadXml(xml);
string  jsonText = JsonConvert.SerializeXmlNode(doc);
//{
//  "?xml": {
//    "@version": "1.0",
//    "@standalone": "no"
//  },
//  "root": {
//    "person": [
//      {
//        "@id": "1",
//        "name": "Alan",
//        "url": "http://www.google.com"
//      },
//      {
//        "@id": "2",
//        "name": "Louis",
//        "url": "http://www.yahoo.com"
//      }
//    ]
//  }
//}   
 
JSON TO XML    
string  json =  @"{
   ""?xml"": {
     ""@version"": ""1.0"",
     ""@standalone"": ""no""
   },
   ""root"": {
     ""person"": [
       {
         ""@id"": ""1"",
         ""name"": ""Alan"",
         ""url"": ""http://www.google.com""
       },
       {
         ""@id"": ""2"",
         ""name"": ""Louis"",
         ""url"": ""http://www.yahoo.com""
       }
     ]
   }
}" ;
  
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
//
//
//  
//   Alan
//   http://www.google.com
//  
//  
//   Louis
//   http://www.yahoo.com
//  
//

  

DEMO:JSON TO XML 

string  json_str =  "{\"a\":\"a\",\"b\":\"b\"}" ;
//json 的字符串需要按照这个格式 书写,否则会报错
string  json =  @"{
   ""?xml"": {
     ""@version"": ""1.0"",
     ""@standalone"": ""no""
   },
   ""root"":"  + json_str + "}"; 
if  (! string .IsNullOrEmpty(json))
{
     XmlDocument doc = JsonConvert.DeserializeXmlNode(json);      
}
这个个方法可以直接使用

public static XmlDocument JsonToXml(string json)
{
XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
return doc;
}
// 从一个对象信息生成Json串
public static string ObjectToJson(object obj)
{
string json = null;
//StringBuilder sb = new StringBuilder();
//JsonSerializer serialize = new JsonSerializer();
//serialize.Serialize
DataContractJsonSerializer serialize = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serialize.WriteObject(ms, obj);
byte[] readbyte = new byte[ms.Length];
ms.Read(readbyte, 0, (int)ms.Length);
json = Encoding.UTF8.GetString(readbyte);
return json;
}
// 从一个Json串生成对象信息
public static object JsonToObject(string jsonString, object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
return serializer.ReadObject(mStream);
}

你可能感兴趣的:(JSON格式转换成XML格式)