Json.NET supports converting JSON to XML and vice versa using the XmlNodeConverter.

Elements, attributes, text, comments, character data, processing instructions, namespaces, and the XML declaration are all preserved when converting between the two. The only caveat is that it is possible to lose the order of differently named nodes at the same level when they are grouped together into an array.

Conversion Rules
  • Elements remain unchanged.

  • Attributes are prefixed with an @ and should be at the start of the object.

  • Single child text nodes are a value directly against an element, otherwise they are accessed via #text.

  • The XML declaration and processing instructions are prefixed with ?.

  • Character data, comments, whitespace and significant whitespace nodes are accessed via #cdata-section, #comment, #whitespace and #significant-whitespace respectively.

  • Multiple nodes with the same name at the same level are grouped together into an array.

  • Empty elements are null.

If the XML created from JSON doesn't match what you want, then you will need to convert it manually. The best approach to do this is to load your JSON into a LINQ to JSON object like JObject or JArray and then use LINQ to create an XDocument. The opposite process, using LINQ with an XDocument to create a JObject or JArray, also works. You can find out more about using LINQ to JSON with LINQ here.

 Note

The version of Json.NET being used in your application will change what XML conversion methods are available. SerializeXmlNode/DeserializeXmlNode are available when the framework supports XmlDocument; SerializeXNode/DeserializeXNode are available when the framework supports XDocument.

SerializeXmlNode

The JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode(). This method takes an XmlNode and serializes it to JSON text.

Converting XML to JSON with SerializeXmlNode
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"
// }
// ]
// }
//}

Because multiple nodes with the same name at the same level are grouped together into an array, the conversion process can produce different JSON depending on the number of nodes. For example, if some XML for a user has a single <Role> node, then that role will be text against a JSON "Role" property, but if the user has multiple <Role> nodes, then the role values will be placed in a JSON array.

To fix this situation a custom XML attribute can be added to force a JSON array to be created.

Attribute to Force a JSON Array
string xml = @"<person id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role>Admin1</role>
</person>"; XmlDocument doc = new XmlDocument();
doc.LoadXml(xml); string json = JsonConvert.SerializeXmlNode(doc);
//{
// "person": {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com",
// "role": "Admin1"
// }
//} xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array='true'>Admin</role>
</person>"; doc = new XmlDocument();
doc.LoadXml(xml); json = JsonConvert.SerializeXmlNode(doc);
//{
// "person": {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com",
// "role": [
// "Admin"
// ]
// }
//}
DeserializeXmlNode

The second helper method on JsonConvert is DeserializeXmlNode(). This method takes JSON text and deserializes it into an XmlNode.

Because valid XML must have one root element, the JSON passed to DeserializeXmlNode should have one property in the root JSON object. If the root JSON object has multiple properties, then the overload that also takes an element name should be used. A root element with that name will be inserted into the deserialized XmlNode.

Converting JSON to XML with DeserializeXmlNode
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>
See Also

Json.NET Converting between JSON and XML的更多相关文章

  1. Json、JavaBean、Map、XML之间的互转

    思路是JavaBean.Map.XML都可以用工具类很简单的转换为Json,进而实现互相转换 1.Map.XML与Json互转 mvn依赖 <dependency> <groupId ...

  2. 常用模块之 shutil,json,pickle,shelve,xml,configparser

    shutil 高级的文件.文件夹.压缩包 处理模块 shutil.copyfileobj(fsrc, fdst[, length]) 将文件内容拷贝到另一个文件中 import shutil shut ...

  3. 常用文件操作模块json,pickle、shelve和XML

    一.json 和 pickle模块 用于序列化的两个模块 json,用于字符串 和 python数据类型间进行转换 pickle,用于python特有的类型 和 python的数据类型间进行转换 Js ...

  4. Java:JSON解析工具-org.json

    一.简介 org.json是Java常用的Json解析工具,主要提供JSONObject和JSONArray类,现在就各个类的使用解释如下. 二.准备 1.在使用org.json之前,我们应该先从该网 ...

  5. json和jsonp(json是目的,jsonp是手段)

    自己理解:JSON是一种数据交换格式,而JSONP是一种依靠开发人员的聪明才智创造出的一种非官方跨域数据交互协议.我们拿最近比较火的谍战片来打个比方,JSON是地下党们用来书写和交换情报的" ...

  6. javascript中字符串格式json如何转化成json对象

    什么是JSON JSON(JavaScript Object Notation)是一种优美的JavaScript对象创建方法.JSON也是一种轻量级数据交换格式.JSON非常易于人阅读与编写,同时利于 ...

  7. JSON之三:获取JSON文本并解释(以google的天气API为例)

    google提供了天气的api,以广州天气为例,地址为: http://api.openweathermap.org/data/2.5/weather?q=guangzhou 返回的结果为: {   ...

  8. json解包与json封包

    首先,对两个名词进行简单的说明: 1.NSData 用来存储二进制的数据类型.NSData类提供了一种简单的方式,它用来设置缓冲区.将文件的内容读入缓冲区,或将缓冲区的内容写到一个文件.不变缓冲区(N ...

  9. JSON以及Java转换JSON的方法(前后端常用处理方法)

    )); map.put("arr", new String[] { "a", "b" }); map.put("func" ...

  10. c# 在.NET使用Newtonsoft.Json转换,读取,写入json

    转自:http://blog.sina.com.cn/s/blog_70686f3a0101kemg.html  首先,大家要明白什么是json,了解更多关于json方面资料大家可以点击https:/ ...

随机推荐

  1. 视频播放测试地址(MP4、M3U8 格式)

    最近在开发视频播放相关的业务功能,开发测试时,需要涉及到 MP4.M3U8 等视频格式. 我每次找测试视频地址时,都要找很久,现在把我在网上收集到的 MP4.M3U8 格式视频地址放在这里,希望帮助到 ...

  2. C#开发的PhotoNet看图软件 - 开源研究系列文章 - 个人小作品

    这几天忙于编程.上次发布了壁纸管理器的插件版( https://www.cnblogs.com/lzhdim/p/18074135 ),然后整理和添加了一下相关的壁纸图片文件,虽然在管理器中也能浏览壁 ...

  3. kubelet 原理分析

    Reference https://atbug.com/kubelet-source-code-analysis/ kubelet 简介 kubernetes 分为控制面和数据面,kubelet 就是 ...

  4. vscode使用npm安装依赖报错

    1.报错信息 npm ERR! code EPERM npm ERR! syscall open npm ERR! path C:\Node\node_cache_cacache\index-v5\4 ...

  5. 力扣575(java&python)-分糖果(简单)

    题目: Alice 有 n 枚糖,其中第 i 枚糖的类型为 candyType[i] .Alice 注意到她的体重正在增长,所以前去拜访了一位医生. 医生建议 Alice 要少摄入糖分,只吃掉她所有糖 ...

  6. Dragonfly 基于 P2P 的文件和镜像分发系统

    简介: 业界软件生态在优化 HTTPS 的性能上也做了诸多探索,传统的软件优化方案在软件层面的优化无法满足流量日益增长的速度,CPU 硬件加速成为业界一个通用的解决方案. 作者:孙景文.吴迪   背景 ...

  7. Ingress Nginx 接连披露高危安全漏洞,是否有更好的选择?

    简介: 在<K8s 网关选型初判:Nginx 还是 Envoy>一文中,我们已经给出了这个新的选项:MSE 云原生网关.本文继续展开分析,为何 MSE 云原生网关有更好的安全性保障. 作者 ...

  8. Apache RocketMQ 的 Service Mesh 开源之旅

    作者 | 凌楚   阿里巴巴开发工程师 导读:自 19 年底开始,支持 Apache RocketMQ 的 Network Filter 历时 4 个月的 Code Review(Pull Reque ...

  9. Mobius 一个运行在 .NET Core 上的 .NET 运行时

    一个 .NET 应用仅仅只是一块在 .NET 运行时上面运行的二进制代码.而 .NET 运行时只是一个能执行这项任务的程序.当前的 .NET Framework 和 .NET Core 运行时采用 C ...

  10. 2018-2-13-win10-uwp-修改CalendarDatePicker图标颜色

    title author date CreateTime categories win10 uwp 修改CalendarDatePicker图标颜色 lindexi 2018-2-13 17:23:3 ...