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

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

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

1、用XMLDocument来解析

 XmlDocument xmlDocument = new XmlDocument();
 xmlDocument.Load("test.xml");
 
 //创建新节点 
 XmlElement nn = xmlDocument.CreateElement("image");
 nn.SetAttribute("imageUrl", "6.jpg");
 
 XmlNode node = xmlDocument.SelectSingleNode("content/section/page/gall/folder");//定位到folder节点
 node.AppendChild(nn);//附加新节点
 
 //保存
 xmlDocument.Save("test.xml");

2、用Linq to XML来解析

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

            XElement root = XElement.Load("test.xml");
            foreach (XAttribute att in root.Attributes())
            {
                root.Add(new XElement(att.Name, (string)att));
            }
            Console.WriteLine(root);

3、附一个详细点的例子

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

<?xml version="1.0" encoding="utf-8"?>
<Car>
  <carcost>
    <ID>20130821133126</ID>
    <uptime>60</uptime>
    <downtime>30</downtime>
    <price>0.4</price>
  </carcost>
  <carcost>
    <ID>20130821014316</ID>
    <uptime>120</uptime>
    <downtime>60</downtime>
    <price>0.3</price>
  </carcost>
  <carcost>
    <ID>20130822043127</ID>
    <uptime>30</uptime>
    <downtime>0</downtime>
    <price>0.5</price>
  </carcost>
  <carcost>
    <ID>20130822043341</ID>
    <uptime>120以上!</uptime>
    <downtime>120</downtime>
    <price>0.2</price>
  </carcost>
</Car>
在控制台应用程序中输入如下代码即可。

    class Program
    {
        static void Main(string[] args)
        {
            IList<CarCost> resultList = new List<CarCost>();

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load("test.xml");

            XmlNodeList xmlNodeList = xmlDocument.SelectSingleNode("Car").ChildNodes;
            foreach (XmlNode list in xmlNodeList)
            {
                CarCost carcost = new CarCost
                (
                    list.SelectSingleNode("ID").InnerText,
                    list.SelectSingleNode("uptime").InnerText,
                    list.SelectSingleNode("downtime").InnerText,
                    float.Parse(list.SelectSingleNode("price").InnerText)
                );
                resultList.Add(carcost);
            }

            IEnumerator enumerator = resultList.GetEnumerator();
            while (enumerator.MoveNext())
            {
                CarCost carCost = enumerator.Current as CarCost;
                Console.WriteLine(carCost.ID + " " + carCost.UpTime + " " + carCost.DownTime + " " + carCost.Price);
            }
        }
    }

    public class CarCost
    {
        public CarCost(string id, string uptime, string downtime, float price)
        {
            this.ID = id;
            this.UpTime = uptime;
            this.DownTime = downtime;
            this.Price = price;
        }
        public string ID { get; set; }
        public string UpTime { get; set; }
        public string DownTime { get; set; }
        public float Price { get; set; }
    }

二、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":""}]

首先定义个实体类:

    public class JobInfo
    {
        public string TaskRoleSpaces { get; set; }
        public string TaskRoles { get; set; }
        public string ProxyUserID { get; set; }
        public string UserID { get; set; }
        public string UserName { get; set; }
        public string UserSystemName { get; set; }
        public string OperationName { get; set; }
        public string OperationValue { get; set; }
        public string OperationValueText { get; set; }
        public DateTime SignDate { get; set; }
        public string Comment { get; set; }
        public string FormDataHashCode { get; set; }
        public string SignatureDivID { get; set; }
    }
然后在控制台Main函数内部输入如下代码:

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':''}]
";
 
            List<JobInfo> jobInfoList = JsonConvert.DeserializeObject<List<JobInfo>>(json);
 
            foreach (JobInfo jobInfo in jobInfoList)
            {
                Console.WriteLine("UserName:" + jobInfo.UserName + "UserID:" + jobInfo.UserID);
            }

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

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

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

首先还是定义实体类:

    public class Info
    {
        public string phantom { get; set; }
        public string id { get; set; }
        public data data { get; set; }
    }

    public class data
    {
        public int MID { get; set; }
        public string Name { get; set; }
        public string Des { get; set; }
        public string Disable { get; set; }
        public string Remark { get; set; }
    }
然后在main方法里面,键入:

            string json = @"[{'phantom':true,'id':'20130717001','data':{'MID':1019,'Name':'aaccccc','Des':'cc','Disable':'启用','Remark':'cccc'}}]";
            List<Info> infoList = JsonConvert.DeserializeObject<List<Info>>(json);

            foreach (Info info in infoList)
            {
                Console.WriteLine("id:" + info.data.MID);
            }
按照我们的预期,应该能够得到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}]}}

定义数据结构:

  public class Data
    {
        public Boolean success { get; set; }
        public Data1 data { get; set; }
    }

    public class Data1
    {
        public Int32 id { get; set; }
        public string code { get; set; }
        public string name { get; set; }
        public string location { get; set; }
        public Int32 qty { get; set; }
        public List<Data2> bins { get; set; }
    }

    public class Data2
    {
        public string code { get; set; }
        public string name { get; set; }
        public string location { get; set; }
        public Int32 qty { get; set; }
    }
Main函数:

 class Program
    {
        static void Main(string[] args)
        {
            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}]}}";
            Data data = JsonConvert.DeserializeObject<Data>(json);

            foreach (var item in data.data.bins)
            {
                //输出:JTL-Z38001、JTL-Z38002,其它类似
                Console.WriteLine(item.code);
            }
        }
    }

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

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = "{\"success\":true,\"data\":{\"name\":\"张三\",\"moulds\":{\"stockImport\":true,\"stockExport\":true,\"justifyLocation\":true,\"justifyBin\":false,\"binRelease\":false}}}";
            Data data = JsonConvert.DeserializeObject<Data>(json);
            Console.WriteLine(data.data.moulds.binRelease);//输出False
        }
    }

    public class Data
    {
        public Boolean success { get; set; }
        public Data1 data { get; set; }
    }

    public class Data1
    {
        public string name { get; set; }
        public Data2 moulds { get; set; }
    }

    public class Data2
    {
        public Boolean stockImport { get; set; }
        public Boolean stockExport { get; set; }
        public Boolean justifyLocation { get; set; }
        public Boolean justifyBin { get; set; }
        public Boolean binRelease { get; set; }
    }
}

JSON字符串3:

{

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

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

完整代码如下:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = "{\"success\": true,\"data\": {\"id\": 100001,\"bin\": \"JIT-3JS-2K\",\"targetBin\": \"JIT-3JS-3K\",\"batchs\": [\"B20140101\",\"B20140102\"]}}";
            Data data = JsonConvert.DeserializeObject<Data>(json);

            foreach (var item in data.data.batchs)
            {
                Console.WriteLine(item);//输出:B20140101、B20140102
            }
        }
    }

    public class Data
    {
        public Boolean success { get; set; }

        public Data1 data { get; set; }
    }

    public class Data1
    {
        public Int32 id { get; set; }

        public string bin { get; set; }

        public string targetBin { get; set; }

        public string[] batchs { get; set; }
    }
}

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

比如:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string j = "{success:true,data:{ bin:{code:\"JTL-Z38001\",name:\"奥迪三轮毂\",location:\"A-001\",qty:100}}}";
            JObject jo = (JObject)JsonConvert.DeserializeObject(j);
            Console.WriteLine(jo);
        }
    }

    public class Data
    {
        public Boolean success { get; set; }
        public Data1 data { get; set; }
    }

    public class Data1
    {
        public Data2 bin { get; set; }
    }

    public class Data2
    {
        public string code { get; set; }
        public string name { get; set; }
        public string location { get; set; }
        public Int32 qty { get; set; }
    }
}

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


如果输出内容修改为:

Console.WriteLine(jo["data"]);


继续取bin节点。

Console.WriteLine(jo["data"]["bin"]);


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

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这样的属性,可以无限循环下去,是个典型的树形结构。

完整的代码如下:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Data data = new Data();
            data.id = 1;
            data.value = "cate";
            data.child = new List<Data>() 
            { 
                new Data(){ id=1,value="cate",child=new List<Data>(){}} ,
                new Data(){ id=1,value="cate",child=new List<Data>()
                { 
                    new Data()
                    { 
                        id=2, 
                        value="cate2" , 
                        child = new List<Data>()
                        { 
                            new Data()
                            {
                                id = 3,
                                value = "cate3",
                                child = new List<Data>(){},
                            }
                        },
                    }
                }} ,
            };

            //序列化为json字符串
            string json = JsonConvert.SerializeObject(data);
            Console.WriteLine(json);

            //反序列化为对象
            Data jsonData = JsonConvert.DeserializeObject<Data>(json);
        }
    }

    public class Data
    {
        public int id { get; set; }
        public string value { get; set; }
        public List<Data> child { get; set; }
    }
}

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

 JObject jo = (JObject)JsonConvert.DeserializeObject(json);
 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"
            }
        ]
    }
]


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            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\"}]}]";
            Data[] datas = JsonConvert.DeserializeObject<Data[]>(jsonString);

            foreach (Data data in datas)
            {
                downList[] downList = data.downList;
                line line = data.line;
                upList[] upLists = data.upList;

                //输出
                Console.WriteLine(string.Join(",", line.Id, line.Name, line.icCard));
                foreach (upList upList in upLists)
                {
                    Console.WriteLine(string.Join(",", upList.endTime, upList.startTime, upList.sId, upList.sType));
                }
                Console.WriteLine("-----------------------------------------------");
            }
        }
    }


    public class Data
    {
        public downList[] downList { get; set; }
        public line line { get; set; }
        public upList[] upList { get; set; }
    }

    public class downList
    {

    }

    public class line
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string icCard { get; set; }
    }

    public class upList
    {
        public string endTime { get; set; }

        public string startTime { get; set; }

        public int sId { get; set; }

        public string sType { get; set; }
    }
}

C#对XML、JSON等格式的解析_第1张图片


附Newtonsoft.Json.dll下载地址:下载吧


你可能感兴趣的:(C#对XML、JSON等格式的解析)