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

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]);

            }



        }

 

 

你可能感兴趣的:(Collections)