C# :XML和JSON互转
我们一般在用JSON或者XML作为数据交换的时候,可能定义一个没有真正意义方法的类,其实就是一个关于属性的数据结构,如果对于这种情况,可以将这个类对象作为中介,然后利用C#提供的序列化和反序列化的方法。今天看到一个别人封装好的感觉不错,就转载:
private static string XmlToJSON(XmlDocument xmlDoc)
{
StringBuilder sbJSON = new StringBuilder();
sbJSON.Append("{ ");
XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
sbJSON.Append("}");
return sbJSON.ToString();
} // XmlToJSONnode: Output an XmlElement, possibly as part of a higher array
private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(node.Name) + "\": ");
sbJSON.Append("{");
// Build a sorted list of key-value pairs
// where key is case-sensitive nodeName
// value is an ArrayList of string or XmlElement
// so that we know whether the nodeName is an array or not.
SortedList childNodeNames = new SortedList(); // Add in all node attributes
if( node.Attributes!=null)
foreach (XmlAttribute attr in node.Attributes)
StoreChildNode(childNodeNames,attr.Name,attr.InnerText); // Add in all nodes
foreach (XmlNode cnode in node.ChildNodes)
{
if (cnode is XmlText)
StoreChildNode(childNodeNames, "value", cnode.InnerText);
else if (cnode is XmlElement)
StoreChildNode(childNodeNames, cnode.Name, cnode);
} // Now output all stored info
foreach (string childname in childNodeNames.Keys)
{
ArrayList alChild = (ArrayList)childNodeNames[childname];
if (alChild.Count == )
OutputNode(childname, alChild[], sbJSON, true);
else
{
sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
foreach (object Child in alChild)
OutputNode(childname, Child, sbJSON, false);
sbJSON.Remove(sbJSON.Length - , );
sbJSON.Append(" ], ");
}
}
sbJSON.Remove(sbJSON.Length - , );
sbJSON.Append(" }");
} // StoreChildNode: Store data associated with each nodeName
// so that we know whether the nodeName is an array or not.
private static void StoreChildNode(SortedList childNodeNames, string nodeName, object nodeValue)
{
// Pre-process contraction of XmlElement-s
if (nodeValue is XmlElement)
{
// Convert <aa></aa> into "aa":null
// <aa>xx</aa> into "aa":"xx"
XmlNode cnode = (XmlNode)nodeValue;
if( cnode.Attributes.Count == )
{
XmlNodeList children = cnode.ChildNodes;
if( children.Count==)
nodeValue = null;
else if (children.Count == && (children[] is XmlText))
nodeValue = ((XmlText)(children[])).InnerText;
}
}
// Add nodeValue to ArrayList associated with each nodeName
// If nodeName doesn't exist then add it
object oValuesAL = childNodeNames[nodeName];
ArrayList ValuesAL;
if (oValuesAL == null)
{
ValuesAL = new ArrayList();
childNodeNames[nodeName] = ValuesAL;
}
else
ValuesAL = (ArrayList)oValuesAL;
ValuesAL.Add(nodeValue);
} private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
{
if (alChild == null)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
sbJSON.Append("null");
}
else if (alChild is string)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
string sChild = (string)alChild;
sChild = sChild.Trim();
sbJSON.Append("\"" + SafeJSON(sChild) + "\"");
}
else
XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
sbJSON.Append(", ");
} // Make a string safe for JSON
private static string SafeJSON(string sIn)
{
StringBuilder sbOut = new StringBuilder(sIn.Length);
foreach (char ch in sIn)
{
if (Char.IsControl(ch) || ch == '\'')
{
int ich = (int)ch;
sbOut.Append(@"\u" + ich.ToString("x4"));
continue;
}
else if (ch == '\"' || ch == '\\' || ch == '/')
{
sbOut.Append('\\');
}
sbOut.Append(ch);
}
return sbOut.ToString();
}
/// <summary>
/// json字符串转换为Xml对象
/// </summary>
/// <param name="sJson"></param>
/// <returns></returns>
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("root");
doc.AppendChild(nRoot);
foreach (KeyValuePair<string, object> item in Dic)
{
XmlElement element = doc.CreateElement(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(item.Key);
KeyValue2Xml(element, item);
node.AppendChild(element);
}
}
else if (kValue.GetType() == typeof(object[]))
{
object[] o = kValue as object[];
for (int i = ; i < o.Length; i++)
{
XmlElement xitem = node.OwnerDocument.CreateElement("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);
}
}
参考:http://blog.csdn.net/bancxc/article/details/5450329
http://www.cnblogs.com/yiranleguan/archive/2012/01/11/2318727.html
C# :XML和JSON互转的更多相关文章
- JavaScript实现XML与JSON互转代码(转载)
下面来分享一个关于JavaScript实现XML与JSON互转例子,这里面介绍了国外的三款xml转json的例子,希望这些例子能给你带来帮助. 最近在开发在线XML编辑器,打算使用JSON做为中间格式 ...
- c++实现Xml和json互转【转】
https://blog.csdn.net/kfy2011/article/details/51774242 1.下载c语言的cJson库源码,库很小,只有两个文件cJSON.c和cJSON.h.下载 ...
- SQL2008使用json.net实现XML与JSON互转
借助CLR,首先实现字符串的互转,然后使用存储过程实现JSON2table public class JsonFunction { /// <summary> ...
- JSONUtil(JAVA对象/List与json互转,xml与json互转)
package com.chauvet.utils.json; import java.io.BufferedReader; import java.io.File; import java.io.F ...
- xml与json互转
依赖包: <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib< ...
- xml和json互转
开发过程中有些时候需要把xml和json互转,如某钱X接口入参和出参都是xml格式的,十分蛋疼.特写下面工具类,以留用. 需要引用jar: <!-- https://mvnrepository. ...
- Json、JavaBean、Map、XML之间的互转
思路是JavaBean.Map.XML都可以用工具类很简单的转换为Json,进而实现互相转换 1.Map.XML与Json互转 mvn依赖 <dependency> <groupId ...
- c#通用配置文件读写类(xml,ini,json)
.NET下编写程序的时候经常会使用到配置文件.配置文件格式通常有xml.ini.json等几种,操作不同类型配置文件需要使用不同的方法,操作较为麻烦.特别是针对同时应用不同格式配置文件的时候,很容易引 ...
- c#通用配置文件读写类与格式转换(xml,ini,json)
.NET下编写程序的时候经常会使用到配置文件.配置文件格式通常有xml.ini.json等几种,操作不同类型配置文件需要使用不同的方法,操作较为麻烦.特别是针对同时应用不同格式配置文件的时候,很容易引 ...
随机推荐
- 解决某些手机RadioGroup中的RadioButton不居中的问题
问题:RadioButton中使用android:gravity="center"使其图片文字居中,在我的华为荣耀7手机上居中显示了,但在HUAWEI G606-T00却显示在右侧 ...
- ajax学习笔记1
ajax是什么? ajax即“Asynchronous Javascript + XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术.能够快速的从服务器获得所需数据 ...
- MyBatis拦截器:给参数对象属性赋值
该拦截器的作用:在进行增加.修改等操作时,给数据模型的一些通用操作属性(如:创建人.创建时间.修改人.修改时间等)自动赋值. 该实现是在DAO层拦截,即存入DB前最后一层.后经分析,不是很合理,改为在 ...
- 暑假集训(2)第四弹 ----- 敌兵布阵(hdu1166)
D - 敌兵布阵 Crawling in process... Crawling failed Time Limit:1000MS Memory Limit:32768KB 64bit ...
- undrop for innodb c_parser 源码分析
一,主函数功能: 1,分析命令行参数,保存在全局变量中; 2,打开文件,加载表定义sql,调用分析函数开始处理; 3,打印导入数据的sql语句; 二,文件处理函数,void process_ibfil ...
- win/linux 下使用 psutil 获取进程 CPU / memory / IO 占用信息
psutil - A cross-platform process and system utilities module for Python 1. 安装 pip 安装即可. windows 下需要 ...
- OpenJudge 2802 小游戏 / Poj 1101 The Game
1.链接地址: http://bailian.openjudge.cn/practice/2802 http://poj.org/problem?id=1101 2.题目: 总时间限制: 1000ms ...
- IOPS和Throughput
IOPS和Throughput吞吐量两个参数是衡量存储性能的主要指标.IOPS表示存储每秒传输IO的数量,Throughput吞吐量则表示每秒数据的传输总量.两者在不同的情况下都能表示存储的性能状况, ...
- 支持HTML5新标签
IE8/IE7/IE6支持通过document.createElement方法产生的标签, 可以利用这一特性让这些浏览器支持HTML5新标签, ...
- TweenMax动画库学习(二)
目录 TweenMax动画库学习(一) TweenMax动画库学习(二) TweenMax动画库学习(三) Tw ...