JSON格式转换成XML格式

摘要:
第一种方法:需要使用命名空间System.Runtime.Serialization.Json下面有JsonReaderWriterFactoryXmlDictionaryReaderreader=JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(sJson),XmlDictionaryReaderQuotas.Max)

第一种方法:

需要使用命名空间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

stringxml =@"<?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 =newXmlDocument();
doc.LoadXml(xml);
stringjsonText = 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
stringjson =@"{
""?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

stringjson_str ="{"a":"a","b":"b"}";
//json 的字符串需要按照这个格式 书写,否则会报错
stringjson =@"{
""?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格式》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇C#创建windows服务并定时执行HTTPREFERER伪造方法下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Java几种常用JSON库性能比较

本篇通过JMH来测试一下Java中几种常见的JSON解析库的性能。 每次都在网上看到别人说什么某某库性能是如何如何的好,碾压其他的库。但是百闻不如一见,只有自己亲手测试过的才是最值得相信的。 JSON不管是在Web开发还是服务器开发中是相当常见的数据传输格式,一般情况我们对于JSON解析构造的性能并不需要过于关心,除非是在性能要求比较高的系统。 目前对于J...

springboot2.0 redis EnableCaching的配置和使用

一、前言   关于EnableCaching最简单使用,个人感觉只需提供一个CacheManager的一个实例就好了。springboot为我们提供了cache相关的自动配置。引入cache模块,如下。 二、maven依赖 <dependency> <groupId>org.springframework.boot&...

Spring boot 整合 Jedis

1  概述   1. Jedis是Redis的Java实现的客户端,其API提供了比较全面的Redis命令的支持。       2.Jedis中的方法调用是比较底层的暴露的Redis的API,也即Jedis中的Java方法基本和Redis的API保持着一致,了解Redis的API,也就能熟练的使用Jedis。       3.Jedis使用阻塞的I/O,且...

jQuery之前端国际化jQuery.i18n.properties

jQuery.i18n.properties是一款轻量级的jQuery国际化插件,能实现Web前端的国际化。 国际化英文单词为:Internationalization,又称i18n,“i”为单词的第一个字母,“18”为“i”和“n”之间单词的个数,而“n”代表这个单词的最后一个字母。jQuery.i18n.properties采用.properties文...

前缀树及C++实现

文章   目录     1、什么是Trie树     2、树的构建与查询     3、Trie树的应用     4、C++实现Trie树以及解决一些字符串问题 前缀树 1 什么是Trie树   Trie树,即前缀树,又称单词查找树,字典树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系...

JavaSE基础之double数据类型的格式化

JavaSE基础之double数据类型的格式化 1、double 数据类型的格式化工具类:DoubleFormatUtil.java 1 package cn.com.zfc.util; 2 3 import java.math.BigDecimal; 4 import java.text.DecimalFormat; 5 import jav...