C# xml、json互转换

转自:http://www.studyofnet.com/news/298.html

本文导读:我们一般在用JSON或者XML作为数据交换的时候,可能定义一个没有真正意义方法的类,其实就是一个关于属性的数据结构,如果对于这种情况,可以将这个类对象作为中介,然后利用C#提供的序列化和反序列化的方法。

一、XML和JSON字符串的对应表格

 

1、节点的属性会被对应地转换为JSON对象的成员"attr_name":"attr_value"。如:
 

XML JSON
<xx yy='nn'></xx> { "xx" : { "yy" : "nn" } }
<xx yy=''></xx> { "xx" : { "yy" : "" } }

 

2、没有子节点、属性和内容的节点被转换为成员"child_name":null

 

XML JSON
<xx/> { "xx" : null }

 

3、没有子节点和属性,但是有内容的节点被转换为成员"child_name":"child_text"

 

XML JSON
<xx>yyy</xx> { "xx" : "yyy" }

 

4、其它节点和属性会被适当地转换为"child_name":对象或者"child_name":[elements]对象数组,节点的值会被转换为对象成员的"value",如:

 

XML JSON
<xx yy='nn'><mm>zzz</mm></xx> { "xx" : { "yy" : "nn", "mm" : "zzz" } }
<xx yy='nn'><mm>zzz</mm><mm>aaa</mm></xx> { "xx" : { "yy" : "nn", "mm" : [ "zzz", "aaa" ] } }
<xx><mm>zzz</mm>some text</xx> { "xx" : { "mm" : "zzz", "value" : "some text" } }
<xx value='yyy'>some text<mm>zzz</mm>more text</xx> { "xx" : { "mm" : "zzz", "value" : [ "yyy", "some text", "more text" ] } }

 

5、字符会被安全地转换为JSON字符串。注意该转换不会保证你的JavaScript代码不会受到任何注入攻击,如果其中的内容来自于一段不安全的XML数据源的话。下面这个例子演示了字符的转义:

 

XML JSON
<aa>/z'z''z\yyy</aa> { "aa" : "\/z\u0027z\''z\\yyy" }

 

二、XML转JSON

 

JSON是一个轻量级的数据交换格式,它可以非常容易地被页面的JavaScript编码为对象的形式,从而方便数据操作。

基于AJAX的页面使用XmlHttpRequest对象从服务端接收数据来响应用户的请求,当返回的数据是XML格式时,它可以被转换为JSON格式的字符串从而通过JavaScript更加容易地对数据进行处理。

许多应用程序都将数据存储为XML的格式,而且会将数据以JSON的格式发送到客户端以做进一步处理。要实现这一点,它们必须将XML格式转换为JSON格式。

XML转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("\\"" + 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();
}     

JSON格式转换为XML格式

            
/**//// <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 = 0; 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);
            }
        }

        

 

posted @ 2016-07-25 13:06  周银胜  阅读(638)  评论(0)    收藏  举报