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<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"
// }
// ]
// }
//}
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格式的更多相关文章
- C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串
在工作中,如果需要跟XML打交道,难免会遇到需要把一个类型集合转换成XML格式的情况.之前的方法比较笨拙,需要给不同的类型,各自写一个转换的函数.但是后来接触反射后,就知道可以利用反射去读取一个类型的 ...
- linux环境下deb格式 转换成rpm格式
linux环境下deb格式 转换成rpm格式 使用alien工具转换deb格式到rpm格式 alien_8.87.tar.gz 下载alien_8.87.tar.gz [root@mysqlnode2 ...
- 怎样将M4A音频格式转换成MP3格式
因为MP3音频格式应用的广泛性,所以很多时候我们都需要将不同的音频格式转换成MP3格式的,那么如果我们需要将M4A音频格式转换成MP3格式,我们应该怎样进行实现呢?下面我们就一起来看一下吧. 操作步骤 ...
- 怎样用Google APIs和Google的应用系统进行集成(5)----怎样把Google Tasks的JSON Schema转换成XML的Schema(XSD)?
前面说了一些Google API的介绍,可是在实际的开发其中,我们可能须要把Google RESTful API返回的JSON数据转换成XML数据输入到第三方系统,这在企业应用集成里面很的常见. 那么 ...
- 怎样用Google APIs和Google的应用系统进行集成(8)----怎样把Google Blogger(博客)的JSON Schema转换成XML的Schema(XSD)?
在Google RESTFul API中,Google Blogger API(Google博客API)应该和我们的生活离得近期:由于差点儿非常多人每天都在看博客,都在写博客,都听说过博客.在前面的G ...
- 分别用Excel和python进行日期格式转换成时间戳格式
最近在处理一份驾驶行为方面的数据,其中要用到时间戳,因此就在此与大家一同分享学习一下. 1.什么是时间戳? 时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01 ...
- 怎样将flac音频格式转换成MP3格式
Flac音频格式怎样转换成MP3格式呢?随着现在音频格式的不断多样性,生活中很多时候我们都会遇到音频格式转换的问题,如flac音频转MP3的问题,那么我们应该如何去解决这个问题呢?下面我们就一起去来一 ...
- windwos文档格式转换成unix格式
在工作学习中我们避免不了需要将一些脚本和命令记录在笔记里面,我使用的是有道云笔记,每当我将上次记录在有道云的脚本复制出来进行使用的时候,总会报一些奇怪的错误,要么是包含换行符,要么就是格式不对,但是我 ...
- 将ERF格式转换成PCAP格式
在研究网络流量分析的时候,wireshark默认采用pcap格式.对于用Endace DAG捕捉卡捕获的数据包,一般来说,都是erf格式的.一般来说,此种格式包含了更多了链路层信息.而我们采用wire ...
随机推荐
- putty 实现不用输入用户名密码直接登陆
多谢谢Eric的教程 ,下面是我的简化版,原版为Eric所写 远程登陆Linux服务器有两大著名软件,一个是商业软件securecrt,一个是开源软件putty. 两者的安全性能都很高,发展了多年,值 ...
- php框架-yii
安装 修改权限问题:runtime;web/assets(mac上) 配置cookie加密串 config/web.php 修改cookieValidationKey L12 配置数据库 控制器: 默 ...
- 关于B/S系统在移动端应用的一些注意的地方(不断更新)
1.不要直接把PC端的页面直接搬到移动端来用.这里举个例子:有个活动页面,在PC端和手机端的Safari里展现都好,但是当用手机APP(如手机淘宝)扫码打开后,却没法顺畅的异步获取到jsonp的信息. ...
- ASP.NET生命周期事件顺序
普通页面运行规律 Page_PreInitPage_InitPage_InitCompletePage_PreLoadPage_LoadButton1事件触发!Page_LoadCompletePag ...
- String类源码分析(JDK1.7)
以下学习根据JDK1.7String类源代码做注释 public final class String implements java.io.Serializable, Comparable<S ...
- Oracle RAC LoadBalance
LoadBalance 就是把负载平均的分配到集群中的各个节点,从而提高整体的吞吐能力. Oracle 10g RAC 提供了两种不同的方法来分散负载: 通过Connection Balancing, ...
- 《C和指针》 读书笔记 -- 第10章 结构和联合
1.聚合数据类型能够同时存储超过一个的单独数据,c提供了两种类型的聚合数据类型,数组和结构. 2.[1] struct SIMPLE { int a; }; struct SIMPLE x; [2] ...
- 利用rlwrap配置linux下oracle sqlplus 历史记录回调
.下载rlwrap wget http://utopia.knoware.nl/~hlub/uck/rlwrap/rlwrap-0.42.tar.gz .解压 tar -xvzf rlwrap-0.4 ...
- 关于python多线程编程中join()和setDaemon()的一点儿探究
关于python多线程编程中join()和setDaemon()的用法,这两天我看网上的资料看得头晕脑涨也没看懂,干脆就做一个实验来看看吧. 首先是编写实验的基础代码,创建一个名为MyThread的 ...
- 微软职位内部推荐-SENIOR PRODUCER
微软近期Open的职位: Role Based in Shanghai, ChinaTitle: ProducerWe are seeking a Senior Producer to lead Pr ...