本文實(shí)例講述了ASP.NET中XML轉(zhuǎn)JSON的方法,。具體如下:
一般在許多應(yīng)用程序中都將數(shù)據(jù)存儲(chǔ)為XML的格式,而且會(huì)將數(shù)據(jù)以JSON的格式發(fā)送到客戶端以做進(jìn)一步處理。要實(shí)現(xiàn)這一點(diǎn),它們必須將XML格式轉(zhuǎn)換為JSON格式。
XML轉(zhuǎn)JSON代碼如下:
代碼如下: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("http://"" + SafeJSON(node.Name) + "http://": ");
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)
新聞熱點(diǎn)
疑難解答
圖片精選