這篇文章主要介紹XML與JSON如何進(jìn)行相互轉(zhuǎn)換,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

JOSN簡介
在本系列的第一篇已經(jīng)簡單比較了XML和JSON 時(shí)光機(jī)
JSON:JavaScript 對(duì)象表示法(JavaScript Object Notation)。 JSON 是存儲(chǔ)和交換文本信息的語法。類似 XML。 JSON 比 XML 更小、更快,更易解析。
什么是 JSON?
JSON 指的是 JavaScript 對(duì)象表示法(JavaScript Object Notation) JSON 是輕量級(jí)的文本數(shù)據(jù)交換格式 JSON 獨(dú)立于語言 * JSON 具有自我描述性,更易理解
JSON 使用 JavaScript 語法來描述數(shù)據(jù)對(duì)象,但是 JSON 仍然獨(dú)立于語言和平臺(tái)。JSON 解析器和 JSON 庫支持許多不同的編程語言。
JSON格式化
盡管有許多宣傳關(guān)于 XML 如何擁有跨平臺(tái),跨語言的優(yōu)勢(shì),然而,除非應(yīng)用于 Web Services,否則,在普通的 Web 應(yīng)用中,開發(fā)者經(jīng)常為 XML 的解析傷透了腦筋,無論是服務(wù)器端生成或處理 XML,還是客戶端用 JavaScript 解析 XML,都常常導(dǎo)致復(fù)雜的代碼,極低的開發(fā)效率。實(shí)際上,對(duì)于大多數(shù) Web 應(yīng)用來說,他們根本不需要復(fù)雜的 XML 來傳輸數(shù)據(jù),XML 的擴(kuò)展性很少具有優(yōu)勢(shì),許多 AJAX 應(yīng)用甚至直接返回 HTML 片段來構(gòu)建動(dòng)態(tài) Web 頁面。和返回 XML 并解析它相比,返回 HTML 片段大大降低了系統(tǒng)的復(fù)雜性,但同時(shí)缺少了一定的靈活性
XML2JOSN
借助第三方類庫轉(zhuǎn)換

使用NuGet添加第三方類庫

<code>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"
// }
// ]
// }
//}</code>
對(duì)于每個(gè)表標(biāo)簽的屬性對(duì)應(yīng)JSON中的"@"標(biāo)簽名
如果有多個(gè)同名標(biāo)簽就會(huì)添加到一個(gè)數(shù)組集合中
其他方式轉(zhuǎn)換
1.使用.NET Framework中的JavaScriptSerializer類
首先需要確保你的工程或服務(wù)器支持.NET 4.0或以上版本的Framework,否則無法找到該類。
通過JavaScriptSerializer來實(shí)現(xiàn)。它的名字空間為:System.Web.Script.Serialization
如果要使用它,還須添加
System.Web.Extensions庫文件引用
<code> var xml =
@"<Columns>
<Column Name=""key1"" DataType=""Boolean"">True</Column>
<Column Name=""key2"" DataType=""String"">Hello World</Column>
<Column Name=""key3"" DataType=""Integer"">999</Column>
</Columns>";
var dic = XDocument
.Parse(xml)
.Descendants("Column")
.ToDictionary(
c => c.Attribute("Name").Value,
c => c.Value
);
var json = new JavaScriptSerializer().Serialize(dic);
Console.WriteLine(json);</code>
2.手動(dòng)編寫轉(zhuǎn)換類
<code> public class Xml2JSON
{
public 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 == 1)
OutputNode(childname, alChild[0], sbJSON, true);
else
{
sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
foreach (object Child in alChild)
OutputNode(childname, Child, sbJSON, false);
sbJSON.Remove(sbJSON.Length - 2, 2);
sbJSON.Append(" ], ");
}
}
sbJSON.Remove(sbJSON.Length - 2, 2);
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 == 0)
{
XmlNodeList children = cnode.ChildNodes;
if (children.Count == 0)
nodeValue = null;
else if (children.Count == 1 && (children[0] is XmlText))
nodeValue = ((XmlText)(children[0])).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();
}
}</code>
JOSN2XML
借助第三方類庫轉(zhuǎn)換

<code>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 = JsonConvert.DeserializeXmlNode(json);
doc.Save(@"D:\json.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></code>以上是“XML與JSON如何進(jìn)行相互轉(zhuǎn)換”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
分享名稱:XML與JSON如何進(jìn)行相互轉(zhuǎn)換-創(chuàng)新互聯(lián)
網(wǎng)頁鏈接:http://chinadenli.net/article10/dpgido.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、建站公司、商城網(wǎng)站、搜索引擎優(yōu)化、外貿(mào)建站、企業(yè)網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容