第一种方法:

需要使用命名空间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<string, object> Dic = (Dictionary<string, object>)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<string, object> 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<string, object> Source)
{
          object kValue = Source.Value;
           if (kValue.GetType() == typeof(Dictionary<string, object>))
          {
              foreach (KeyValuePair<string, object> item in kValue as Dictionary<string, object>)
              {
                   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<string, object> item = new KeyValuePair<string, object>("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 </contact>
xmlWriter.WriteEndElement();
// close contacts </contact>
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 = @"<?xml version=""1.0"" standalone=""no""?>

<root>

  <person id=""1"">
  <name>Alan</name>
  <url>http://www.google.com</url>
  </person>
  <person id=""2"">
  <name>Louis</name>
  <url>http://www.yahoo.com</url>
  </person>
</root>";
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);
// <?xml version="1.0" standalone="no"?>
// <root>
//   <person id="1">
//   <name>Alan</name>
//   <url>http://www.google.com</url>
//   </person>
//   <person id="2">
//   <name>Louis</name>
//   <url>http://www.yahoo.com</url>
//   </person>
// </root>

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格式的更多相关文章

  1. C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串

    在工作中,如果需要跟XML打交道,难免会遇到需要把一个类型集合转换成XML格式的情况.之前的方法比较笨拙,需要给不同的类型,各自写一个转换的函数.但是后来接触反射后,就知道可以利用反射去读取一个类型的 ...

  2. linux环境下deb格式 转换成rpm格式

    linux环境下deb格式 转换成rpm格式 使用alien工具转换deb格式到rpm格式 alien_8.87.tar.gz 下载alien_8.87.tar.gz [root@mysqlnode2 ...

  3. 怎样将M4A音频格式转换成MP3格式

    因为MP3音频格式应用的广泛性,所以很多时候我们都需要将不同的音频格式转换成MP3格式的,那么如果我们需要将M4A音频格式转换成MP3格式,我们应该怎样进行实现呢?下面我们就一起来看一下吧. 操作步骤 ...

  4. 怎样用Google APIs和Google的应用系统进行集成(5)----怎样把Google Tasks的JSON Schema转换成XML的Schema(XSD)?

    前面说了一些Google API的介绍,可是在实际的开发其中,我们可能须要把Google RESTful API返回的JSON数据转换成XML数据输入到第三方系统,这在企业应用集成里面很的常见. 那么 ...

  5. 怎样用Google APIs和Google的应用系统进行集成(8)----怎样把Google Blogger(博客)的JSON Schema转换成XML的Schema(XSD)?

    在Google RESTFul API中,Google Blogger API(Google博客API)应该和我们的生活离得近期:由于差点儿非常多人每天都在看博客,都在写博客,都听说过博客.在前面的G ...

  6. 分别用Excel和python进行日期格式转换成时间戳格式

    最近在处理一份驾驶行为方面的数据,其中要用到时间戳,因此就在此与大家一同分享学习一下. 1.什么是时间戳? 时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01 ...

  7. 怎样将flac音频格式转换成MP3格式

    Flac音频格式怎样转换成MP3格式呢?随着现在音频格式的不断多样性,生活中很多时候我们都会遇到音频格式转换的问题,如flac音频转MP3的问题,那么我们应该如何去解决这个问题呢?下面我们就一起去来一 ...

  8. windwos文档格式转换成unix格式

    在工作学习中我们避免不了需要将一些脚本和命令记录在笔记里面,我使用的是有道云笔记,每当我将上次记录在有道云的脚本复制出来进行使用的时候,总会报一些奇怪的错误,要么是包含换行符,要么就是格式不对,但是我 ...

  9. 将ERF格式转换成PCAP格式

    在研究网络流量分析的时候,wireshark默认采用pcap格式.对于用Endace DAG捕捉卡捕获的数据包,一般来说,都是erf格式的.一般来说,此种格式包含了更多了链路层信息.而我们采用wire ...

随机推荐

  1. Java中的队列:java.util.Queue接口

    队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作. Queue接口与List.Set同一级别,都是继承了Collection接口.Linked ...

  2. C#如何获取快捷方式指向的目标文件

    前几天,做个小程序时遇到的问题,在百度上搜索了很久,没有发现好的解决方案,在英文网站上立刻搜到办法,看来还是国外的资源要全面一些,只是Google经常访问不正常,没办法啊. “C#如何获取快捷方式指向 ...

  3. [ Web Service ] [ SOAP ] [ JSON ] [ XML ] 格式轉換

    JSON格式產生器_Demo JSON格式產生器_ObjGen - Live JSON Generator JSON格式整理_JSON Formatter & Validator Online ...

  4. SendMessage 窗口函数

    函数功能:该函数将指定的消息发送到一个或多个窗口.此函数为指定的窗口调用窗口程序,直到窗口程序处理完消息再返回.而函数PostMessage不同,将一个消息寄送到一个线程的消息队列后立即返回. MSD ...

  5. 数据可视化(一)-Matplotlib简易入门

    本节的内容来源:https://www.dataquest.io/mission/10/plotting-basics 本节的数据来源:https://archive.ics.uci.edu/ml/d ...

  6. WPF中Image的Stretch属性

    有时候我们在WPF程序中设置了图片的Width和Height,但图片显示出来的宽和高并不是我们预期的效果,这实际上是由于Image的默认Stretch属性导致的 Image的Stretch属性默认为U ...

  7. clients(PV操作共享内核内存进行输入输出分屏) - server(进程间通信)模型实现

    1.拓扑结构 2.PV操作共享内核内存进行输入输出分屏 (1) int semop(int semid,struct sembuf *sops,size_t nsops): 功能描述 操作一个或一组信 ...

  8. Eclipse 中隐藏的 5 个非常有用的功能

    Eclipse就是一头野兽.它也是一套设备,神秘但更具威力.有些人称它为一个持续变形机.另一些人则称它是一个变异体.不错,它很庞大,需要花费多年才能掌握.而在你好不容易掌握之后,你的老板出现了然后告诉 ...

  9. 类的本质、description方法、SEL、NSLog输出增强

    一.类的本质 1.类也是个对象 其实类也是一个对象,是Class类型的对象,简称“类对象” Class类型的定义 typedef struct objc_class *Class; 类名就代表着类对象 ...

  10. 子查询注意这几点, 就可以写出好的sql语句

    执行sql时子查询的语句一般优先执行 理论上多表查询效率是高于子查询(根据子查询不值一个查询语句可能会有多个from但是多表查询只产生一个from), 但是在oracle中子查询效率一般会高于多表查询