码迷,mamicode.com
首页 > Web开发 > 详细

C# testJsonAsXMLNodeAttribute - XML& json & Collections - XmlNode, XmlElement, XmlAttribute,Dictionary,List

时间:2014-07-06 21:20:53      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   cti   for   

testJsonAsXMLNodeAttribute

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ParseXML
{
    class Program
    {
        static void Main(string[] args)
        {
            testJsonAsXMLNodeAttribute();

        }
        public static void testJsonAsXMLNodeAttribute()
        {


            string path = @"D:\testSSGeneration\XMLforTestSSGeneration.xml";
            string outpath = @"D:\testSSGeneration\xmlWithFunAttr.xml";

            // 1. read xml and insert a json result as a attribute of root node

            XmlDocument doc = new XmlDocument();
            doc.Load(path);


            XmlNode root = doc.FirstChild;
            XmlElement xe = (XmlElement)root; ;//将子节点类型转换为XmlElement类型

            List<string> list = new List<string>();

            list.Add("param1");
            list.Add("param2");

            Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
            dic.Add("ff1", list);
            dic.Add("ff2", list);
            //序列化对象

            string jsonStr = JsonConvert.SerializeObject(dic);//将对象转换成json存储
            xe.SetAttribute("Func", jsonStr);

            // 2. serilization to XMLFile
            doc.Save(outpath);//保存

            // 3. deserilization to XMLFile
            XmlDocument testxmlDoc = new XmlDocument();
            testxmlDoc.Load(outpath);

            XmlNode testroot = testxmlDoc.FirstChild;
            XmlAttributeCollection attrlist = testroot.Attributes;
            XmlAttribute fffattr = attrlist["Func"];

            Console.WriteLine("fffattr.Value: " + fffattr.Value);

            // 4. 将json转换成对象
            Console.WriteLine("fffattr.Value - json");
            Dictionary<string, List<string>> testdic = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(fffattr.Value);

            foreach (KeyValuePair<string, List<string>> kvp in testdic)
            {
                Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value[0]);
            }

        }

 

 

C# testJsonAsXMLNodeAttribute - XML& json & Collections - XmlNode, XmlElement, XmlAttribute,Dictionary,List,布布扣,bubuko.com

C# testJsonAsXMLNodeAttribute - XML& json & Collections - XmlNode, XmlElement, XmlAttribute,Dictionary,List

标签:des   style   blog   color   cti   for   

原文地址:http://www.cnblogs.com/viviancc/p/3824636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!