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. vue3探索——使用ref与$parent实现父子组件间通信

    在vue3中,可以使用vue3的API defineExpose()函数结合ref或者$parent,实现父子组件数据的传递. 子组件向父组件传递数据defineExpose()和ref 子组件:通过 ...

  2. 整理k8s————k8s组件[二]

    前言 简单整理一下k8s 组件. 正文 borg 架构: borgmaster 是处理请求分发的. borglet 是具体运行容器. 这里有一个调度scheduler,这个比较重要吧. 比如说用户通过 ...

  3. 《c#高级编程》第2章C#2.0中的更改(二)——匿名类型

    一.概念 C#中的匿名类型是一种特殊类型,可以在运行时动态创建一个对象,该对象可以包含多个属性,这些属性的名称和类型可以在创建时指定.相对于定义具体的类,匿名类型更加灵活和简洁. C#的匿名类型通常用 ...

  4. 剑指offer39(Java)-数组中出现次数超过一半的数字(简单)

    题目: 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字. 你可以假设数组是非空的,并且给定的数组总是存在多数元素. 示例 1: 输入: [1, 2, 3, 2, 2, 2, 5, 4, ...

  5. 力扣162(java&python)-寻找峰值(中等)

    题目: 峰值元素是指其值严格大于左右相邻值的元素. 给你一个整数数组 nums,找到峰值元素并返回其索引.数组可能包含多个峰值,在这种情况下,返回 任何一个峰值 所在位置即可. 你可以假设 nums[ ...

  6. 力扣412(java)-Fizz Buzz(简单)

    题目: 给你一个整数 n ,找出从 1 到 n 各个整数的 Fizz Buzz 表示,并用字符串数组 answer(下标从 1 开始)返回结果,其中: answer[i] == "FizzB ...

  7. 第 10 章 使用pyecharts 进行数据展示

    第 10 章 使用pyecharts 进行数据展示 10.1 安装 pyecharts pyecharts 是一个用于生成 Echarts 图表的类库, Echarts 是百度开源的一个数据可视化JS ...

  8. 深度解读 MongoDB 最全面的增强版本 4.4 新特性

    MongoDB 在今年正式发布了新的 4.4 大版本,这次的发布包含众多的增强 Feature,可以称之为是一个维护性的版本,而且是一个用户期待已久的维护性版本,MongoDB 官方也把这次发布称为「 ...

  9. [ML] 可视化编写运行 Python 脚本的工具 Jupyter

    Jupyter 提供了可视化的编写和运行 python 程序的 Web 界面. https://jupyter.org/install 使用只需要两步: $ pip install jupyterla ...

  10. WPF 使用 Dispatcher 的 InvokeAsync 和 BeginInvoke 的异常处理差别

    一般认为 WPF 的 Dispatcher 的 InvokeAsync 方法是 BeginInvoke 方法的平替方法和升级版,接近在任何情况下都应该在业务层使用 InvokeAsync 方法代替 B ...