zoukankan      html  css  js  c++  java
  • C#对XML、JSON等格式的解析

    C#对XML、JSON等格式的解析

    一、C#对XML格式数据的解析

    1、用XMLDocument来解析

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. XmlDocument xmlDocument = new XmlDocument();  
    2. xmlDocument.Load("test.xml");  
    3.   
    4. //创建新节点   
    5. XmlElement nn = xmlDocument.CreateElement("image");  
    6. nn.SetAttribute("imageUrl", "6.jpg");  
    7.   
    8. XmlNode node = xmlDocument.SelectSingleNode("content/section/page/gall/folder");//定位到folder节点  
    9. node.AppendChild(nn);//附加新节点  
    10.   
    11. //保存  
    12. xmlDocument.Save("test.xml");  

    2、用Linq to XML来解析

    可以通过遍历,来获得你想要的节点的内容或属性

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. XElement root = XElement.Load("test.xml");  
    2. foreach (XAttribute att in root.Attributes())  
    3. {  
    4.     root.Add(new XElement(att.Name, (string)att));  
    5. }  
    6. Console.WriteLine(root);  

    3、附一个详细点的例子

    比如要解析如下的xml文件,将其转化为Ilist对象。

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <Car>  
    3.   <carcost>  
    4.     <ID>20130821133126</ID>  
    5.     <uptime>60</uptime>  
    6.     <downtime>30</downtime>  
    7.     <price>0.4</price>  
    8.   </carcost>  
    9.   <carcost>  
    10.     <ID>20130821014316</ID>  
    11.     <uptime>120</uptime>  
    12.     <downtime>60</downtime>  
    13.     <price>0.3</price>  
    14.   </carcost>  
    15.   <carcost>  
    16.     <ID>20130822043127</ID>  
    17.     <uptime>30</uptime>  
    18.     <downtime>0</downtime>  
    19.     <price>0.5</price>  
    20.   </carcost>  
    21.   <carcost>  
    22.     <ID>20130822043341</ID>  
    23.     <uptime>120以上!</uptime>  
    24.     <downtime>120</downtime>  
    25.     <price>0.2</price>  
    26.   </carcost>  
    27. </Car>  

    在控制台应用程序中输入如下代码即可。

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. class Program  
    2. {  
    3.     static void Main(string[] args)  
    4.     {  
    5.         IList<CarCost> resultList = new List<CarCost>();  
    6.   
    7.         XmlDocument xmlDocument = new XmlDocument();  
    8.         xmlDocument.Load("test.xml");  
    9.   
    10.         XmlNodeList xmlNodeList = xmlDocument.SelectSingleNode("Car").ChildNodes;  
    11.         foreach (XmlNode list in xmlNodeList)  
    12.         {  
    13.             CarCost carcost = new CarCost  
    14.             (  
    15.                 list.SelectSingleNode("ID").InnerText,  
    16.                 list.SelectSingleNode("uptime").InnerText,  
    17.                 list.SelectSingleNode("downtime").InnerText,  
    18.                 float.Parse(list.SelectSingleNode("price").InnerText)  
    19.             );  
    20.             resultList.Add(carcost);  
    21.         }  
    22.   
    23.         IEnumerator enumerator = resultList.GetEnumerator();  
    24.         while (enumerator.MoveNext())  
    25.         {  
    26.             CarCost carCost = enumerator.Current as CarCost;  
    27.             Console.WriteLine(carCost.ID + " " + carCost.UpTime + " " + carCost.DownTime + " " + carCost.Price);  
    28.         }  
    29.     }  
    30. }  
    31.   
    32. public class CarCost  
    33. {  
    34.     public CarCost(string id, string uptime, string downtime, float price)  
    35.     {  
    36.         this.ID = id;  
    37.         this.UpTime = uptime;  
    38.         this.DownTime = downtime;  
    39.         this.Price = price;  
    40.     }  
    41.     public string ID { get; set; }  
    42.     public string UpTime { get; set; }  
    43.     public string DownTime { get; set; }  
    44.     public float Price { get; set; }  
    45. }  

    二、C#对JSON格式数据的解析

    引用Newtonsoft.Json.dll文件,来解析。

    比如:有个要解析的JSON字符串

    [{"TaskRoleSpaces":"","TaskRoles":"","ProxyUserID":"5d9ad5dc1c5e494db1d1b4d8d79b60a7","UserID":"5d9ad5dc1c5e494db1d1b4d8d79b60a7","UserName":"姓名","UserSystemName":"2234","OperationName":"送合同负责人","OperationValue":"同意","OperationValueText":"","SignDate":"2013-06-19 10:31:26","Comment":"同意","FormDataHashCode":"","SignatureDivID":""},{"TaskRoleSpaces":"","TaskRoles":"","ProxyUserID":"2c96c3943826ea93013826eafe6d0089","UserID":"2c96c3943826ea93013826eafe6d0089","UserName":"姓名2","UserSystemName":"1234","OperationName":"送合同负责人","OperationValue":"同意","OperationValueText":"","SignDate":"2013-06-20 09:37:11","Comment":"同意","FormDataHashCode":"","SignatureDivID":""}]

    首先定义个实体类:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. public class JobInfo  
    2. {  
    3.     public string TaskRoleSpaces { get; set; }  
    4.     public string TaskRoles { get; set; }  
    5.     public string ProxyUserID { get; set; }  
    6.     public string UserID { get; set; }  
    7.     public string UserName { get; set; }  
    8.     public string UserSystemName { get; set; }  
    9.     public string OperationName { get; set; }  
    10.     public string OperationValue { get; set; }  
    11.     public string OperationValueText { get; set; }  
    12.     public DateTime SignDate { get; set; }  
    13.     public string Comment { get; set; }  
    14.     public string FormDataHashCode { get; set; }  
    15.     public string SignatureDivID { get; set; }  
    16. }  

    然后在控制台Main函数内部输入如下代码:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. string json = @"[{'TaskRoleSpaces':'','TaskRoles':'','ProxyUserID':'5d9ad5dc1c5e494db1d1b4d8d79b60a7','UserID':'5d9ad5dc1c5e494db1d1b4d8d79b60a7','UserName':'姓名','UserSystemName':'2234','OperationName':'送合同负责人','OperationValue':'同意','OperationValueText':'','SignDate':'2013-06-19 10:31:26','Comment':'同意','FormDataHashCode':'','SignatureDivID':''},{'TaskRoleSpaces':'','TaskRoles':'','ProxyUserID':'2c96c3943826ea93013826eafe6d0089','UserID':'2c96c3943826ea93013826eafe6d0089','UserName':'姓名2','UserSystemName':'1234','OperationName':'送合同负责人','OperationValue':'同意','OperationValueText':'','SignDate':'2013-06-20 09:37:11','Comment':'同意','FormDataHashCode':'','SignatureDivID':''}]  
    2. ";  
    3.    
    4.             List<JobInfo> jobInfoList = JsonConvert.DeserializeObject<List<JobInfo>>(json);  
    5.    
    6.             foreach (JobInfo jobInfo in jobInfoList)  
    7.             {  
    8.                 Console.WriteLine("UserName:" + jobInfo.UserName + "UserID:" + jobInfo.UserID);  
    9.             }  

    这样就可以正常输出内容了。

    我想肯定有人会问,如果有多层关系的json字符串该如何处理呢?没关系,一样的处理。

    比如如何解析这个json字符串:[{'phantom':true,'id':'20130717001','data':{'MID':1019,'Name':'aaccccc','Des':'cc','Disable':'启用','Remark':'cccc'}}]  ?

    首先还是定义实体类:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. public class Info  
    2. {  
    3.     public string phantom { get; set; }  
    4.     public string id { get; set; }  
    5.     public data data { get; set; }  
    6. }  
    7.   
    8. public class data  
    9. {  
    10.     public int MID { get; set; }  
    11.     public string Name { get; set; }  
    12.     public string Des { get; set; }  
    13.     public string Disable { get; set; }  
    14.     public string Remark { get; set; }  
    15. }  

    然后在main方法里面,键入:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. string json = @"[{'phantom':true,'id':'20130717001','data':{'MID':1019,'Name':'aaccccc','Des':'cc','Disable':'启用','Remark':'cccc'}}]";  
    2. List<Info> infoList = JsonConvert.DeserializeObject<List<Info>>(json);  
    3.   
    4. foreach (Info info in infoList)  
    5. {  
    6.     Console.WriteLine("id:" + info.data.MID);  
    7. }  

    按照我们的预期,应该能够得到1019的结果。

    截图为证:

    —————————————————————————————————————————————————————————————————————————————

    再附一个JSON解析的例子,来自于兔子家族—二哥在本篇博客下的回复。

    JSON字符串1:{success:true,data:{id:100001,code:"JTL-Z38005",name:"奥迪三轮毂",location:"A-202",qty:100,bins:[{code:"JTL-Z38001",name:"奥迪三轮毂",location:"A-001",qty:100},{ code:"JTL-Z38002",name:"奥迪三轮毂",location:"A-002",qty:100}]}}

    定义数据结构:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. public class Data  
    2.   {  
    3.       public Boolean success { get; set; }  
    4.       public Data1 data { get; set; }  
    5.   }  
    6.   
    7.   public class Data1  
    8.   {  
    9.       public Int32 id { get; set; }  
    10.       public string code { get; set; }  
    11.       public string name { get; set; }  
    12.       public string location { get; set; }  
    13.       public Int32 qty { get; set; }  
    14.       public List<Data2> bins { get; set; }  
    15.   }  
    16.   
    17.   public class Data2  
    18.   {  
    19.       public string code { get; set; }  
    20.       public string name { get; set; }  
    21.       public string location { get; set; }  
    22.       public Int32 qty { get; set; }  
    23.   }  

    Main函数:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. class Program  
    2.    {  
    3.        static void Main(string[] args)  
    4.        {  
    5.            string json = "{success:true,data:{id:100001,code:"JTL-Z38005",name:"奥迪三轮毂",location:"A-202",qty:100,bins:[{code:"JTL-Z38001",name:"奥迪三轮毂",location:"A-001",qty:100},{ code:"JTL-Z38002",name:"奥迪三轮毂",location:"A-002",qty:100}]}}";  
    6.            Data data = JsonConvert.DeserializeObject<Data>(json);  
    7.   
    8.            foreach (var item in data.data.bins)  
    9.            {  
    10.                //输出:JTL-Z38001、JTL-Z38002,其它类似  
    11.                Console.WriteLine(item.code);  
    12.            }  
    13.        }  
    14.    }  


    JSON字符串2:{"success":true,"data":{"name":"张三","moulds":{"stockImport":true,"stockExport":true,"justifyLocation":true,"justifyBin":false,"binRelease":false}}}

    在控制台应用程序下的完整代码:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. namespace ConsoleApplication1  
    2. {  
    3.     class Program  
    4.     {  
    5.         static void Main(string[] args)  
    6.         {  
    7.             string json = "{"success":true,"data":{"name":"张三","moulds":{"stockImport":true,"stockExport":true,"justifyLocation":true,"justifyBin":false,"binRelease":false}}}";  
    8.             Data data = JsonConvert.DeserializeObject<Data>(json);  
    9.             Console.WriteLine(data.data.moulds.binRelease);//输出False  
    10.         }  
    11.     }  
    12.   
    13.     public class Data  
    14.     {  
    15.         public Boolean success { get; set; }  
    16.         public Data1 data { get; set; }  
    17.     }  
    18.   
    19.     public class Data1  
    20.     {  
    21.         public string name { get; set; }  
    22.         public Data2 moulds { get; set; }  
    23.     }  
    24.   
    25.     public class Data2  
    26.     {  
    27.         public Boolean stockImport { get; set; }  
    28.         public Boolean stockExport { get; set; }  
    29.         public Boolean justifyLocation { get; set; }  
    30.         public Boolean justifyBin { get; set; }  
    31.         public Boolean binRelease { get; set; }  
    32.     }  
    33. }  

    JSON字符串3:

    {

        "success": true,
        "data": {
            "id": 100001,
            "bin": "JIT-3JS-2K",
            "targetBin": "JIT-3JS-3K",
            "batchs": [
                "B20140101",
                "B20140102"
            ]
        }
    }

    他的问题主要是不知道batchs这里怎么处理,其实很简单就是一个数组而已。

    完整代码如下:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. namespace ConsoleApplication1  
    2. {  
    3.     class Program  
    4.     {  
    5.         static void Main(string[] args)  
    6.         {  
    7.             string json = "{"success": true,"data": {"id": 100001,"bin": "JIT-3JS-2K","targetBin": "JIT-3JS-3K","batchs": ["B20140101","B20140102"]}}";  
    8.             Data data = JsonConvert.DeserializeObject<Data>(json);  
    9.   
    10.             foreach (var item in data.data.batchs)  
    11.             {  
    12.                 Console.WriteLine(item);//输出:B20140101、B20140102  
    13.             }  
    14.         }  
    15.     }  
    16.   
    17.     public class Data  
    18.     {  
    19.         public Boolean success { get; set; }  
    20.   
    21.         public Data1 data { get; set; }  
    22.     }  
    23.   
    24.     public class Data1  
    25.     {  
    26.         public Int32 id { get; set; }  
    27.   
    28.         public string bin { get; set; }  
    29.   
    30.         public string targetBin { get; set; }  
    31.   
    32.         public string[] batchs { get; set; }  
    33.     }  
    34. }  

    除了上述返回类的实体对象做法之外,JSON.NET还提供了JObject类,可以取自己指定节点的内容。

    比如:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. namespace ConsoleApplication1  
    2. {  
    3.     class Program  
    4.     {  
    5.         static void Main(string[] args)  
    6.         {  
    7.             string j = "{success:true,data:{ bin:{code:"JTL-Z38001",name:"奥迪三轮毂",location:"A-001",qty:100}}}";  
    8.             JObject jo = (JObject)JsonConvert.DeserializeObject(j);  
    9.             Console.WriteLine(jo);  
    10.         }  
    11.     }  
    12.   
    13.     public class Data  
    14.     {  
    15.         public Boolean success { get; set; }  
    16.         public Data1 data { get; set; }  
    17.     }  
    18.   
    19.     public class Data1  
    20.     {  
    21.         public Data2 bin { get; set; }  
    22.     }  
    23.   
    24.     public class Data2  
    25.     {  
    26.         public string code { get; set; }  
    27.         public string name { get; set; }  
    28.         public string location { get; set; }  
    29.         public Int32 qty { get; set; }  
    30.     }  
    31. }  


    直接运行,返回结果如下:

    如果输出内容修改为:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. Console.WriteLine(jo["data"]);  

    继续取bin节点。

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. Console.WriteLine(jo["data"]["bin"]);  

    最后我们取其中name对应的value。

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. Console.WriteLine(jo["data"]["bin"]["name"]);  

    一步一步的获取了JSON字符串对应的Value。

    —————————————————————————————————————————————————————————————————————————————

    群里有人提出一个问题,比如我要生成如下的JSON字符串,该如何处理呢?

    {
        "id": 1,
        "value": "cate",
        "child": [
            {
                "id": 1,
                "value": "cate",
                "child": [
                    
                ]
            },
            {
                "id": 1,
                "value": "cate",
                "child": [
                    {
                        "id": 2,
                        "value": "cate2",
                        "child": [
                            {
                                "id": 3,
                                "value": "cate3",
                                "child": [
                                    
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }

    通过观察我们会发现,其实规律比较好找,就是包含id、value、child这样的属性,child又包含id、value、child这样的属性,可以无限循环下去,是个典型的树形结构。

    完整的代码如下:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. namespace ConsoleApplication1  
    2. {  
    3.     class Program  
    4.     {  
    5.         static void Main(string[] args)  
    6.         {  
    7.             Data data = new Data();  
    8.             data.id = 1;  
    9.             data.value = "cate";  
    10.             data.child = new List<Data>()   
    11.             {   
    12.                 new Data(){ id=1,value="cate",child=new List<Data>(){}} ,  
    13.                 new Data(){ id=1,value="cate",child=new List<Data>()  
    14.                 {   
    15.                     new Data()  
    16.                     {   
    17.                         id=2,   
    18.                         value="cate2" ,   
    19.                         child = new List<Data>()  
    20.                         {   
    21.                             new Data()  
    22.                             {  
    23.                                 id = 3,  
    24.                                 value = "cate3",  
    25.                                 child = new List<Data>(){},  
    26.                             }  
    27.                         },  
    28.                     }  
    29.                 }} ,  
    30.             };  
    31.   
    32.             //序列化为json字符串  
    33.             string json = JsonConvert.SerializeObject(data);  
    34.             Console.WriteLine(json);  
    35.   
    36.             //反序列化为对象  
    37.             Data jsonData = JsonConvert.DeserializeObject<Data>(json);  
    38.         }  
    39.     }  
    40.   
    41.     public class Data  
    42.     {  
    43.         public int id { get; set; }  
    44.         public string value { get; set; }  
    45.         public List<Data> child { get; set; }  
    46.     }  
    47. }  

    我们验证一下生成的结果:

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. JObject jo = (JObject)JsonConvert.DeserializeObject(json);  
    2. Console.WriteLine(jo);  

    再来一个复杂点的JSON结构:

    [
        {
            "downList": [],
            "line": {
                "Id": -1,
                "Name": "admin",
                "icCard": "1"
            },
            "upList": [
                {
                    "endTime": "18:10",
                    "startTime": "06:40",
                    "sId": 385,
                    "sType": "38"
                },
                {
                    "endTime": "18:10",
                    "startTime": "06:40",
                    "sId": 1036,
                    "sType": "38"
                }
            ]
        },
        {
            "downList": [],
            "line": {
                "Id": -1,
                "Name": "admin",
                "icCard": "1"
            },
            "upList": [
                {
                    "endTime": "18:10",
                    "startTime": "06:40",
                    "sId": 385,
                    "sType": "38"
                },
                {
                    "endTime": "18:10",
                    "startTime": "06:40",
                    "sId": 1036,
                    "sType": "38"
                }
            ]
        }
    ]

    [csharp] view plaincopy在CODE上查看代码片派生到我的代码片
     
     
    1. namespace ConsoleApplication1  
    2. {  
    3.     class Program  
    4.     {  
    5.         static void Main(string[] args)  
    6.         {  
    7.             string jsonString = "[{"downList": [],"line": {"Id": -1,"Name": "admin","icCard": "1"},"upList": [{"endTime": "18:10","startTime": "06:40","sId": 385,"sType": "38"},{"endTime": "18:10","startTime": "06:40","sId": 1036,"sType": "38"}]},{"downList": [],"line": {"Id": -1,"Name": "admin","icCard": "1"},"upList": [{"endTime": "18:10","startTime": "06:40","sId": 385,"sType": "38"},{"endTime": "18:10","startTime": "06:40","sId": 1036,"sType": "38"}]}]";  
    8.             Data[] datas = JsonConvert.DeserializeObject<Data[]>(jsonString);  
    9.   
    10.             foreach (Data data in datas)  
    11.             {  
    12.                 downList[] downList = data.downList;  
    13.                 line line = data.line;  
    14.                 upList[] upLists = data.upList;  
    15.   
    16.                 //输出  
    17.                 Console.WriteLine(string.Join(",", line.Id, line.Name, line.icCard));  
    18.                 foreach (upList upList in upLists)  
    19.                 {  
    20.                     Console.WriteLine(string.Join(",", upList.endTime, upList.startTime, upList.sId, upList.sType));  
    21.                 }  
    22.                 Console.WriteLine("-----------------------------------------------");  
    23.             }  
    24.         }  
    25.     }  
    26.   
    27.   
    28.     public class Data  
    29.     {  
    30.         public downList[] downList { get; set; }  
    31.         public line line { get; set; }  
    32.         public upList[] upList { get; set; }  
    33.     }  
    34.   
    35.     public class downList  
    36.     {  
    37.   
    38.     }  
    39.   
    40.     public class line  
    41.     {  
    42.         public int Id { get; set; }  
    43.         public string Name { get; set; }  
    44.         public string icCard { get; set; }  
    45.     }  
    46.   
    47.     public class upList  
    48.     {  
    49.         public string endTime { get; set; }  
    50.   
    51.         public string startTime { get; set; }  
    52.   
    53.         public int sId { get; set; }  
    54.   
    55.         public string sType { get; set; }  
    56.     }  
    57. }  
  • 相关阅读:
    利用cookie实现iframe刷新时停留在当前页面
    css定位学习经验记录
    用div加css做表格去掉外围边框
    利用css中的background-position定位图片
    css3实现圆形逐渐减少动画
    The Best Path
    3998
    YAPTCHA(hdu2973)
    1556 计算
    1808: 地铁
  • 原文地址:https://www.cnblogs.com/lpbca/p/5870790.html
Copyright © 2011-2022 走看看