詳解C#對XML、JSON等格式的解析_C#教程

來源:互聯網
上載者:User

一、C#對XML格式資料的解析

1、用XMLDocument來解析

XmlDocument xmlDocument = new XmlDocument(); xmlDocumentLoad("testxml");  //建立新節點  XmlElement nn = xmlDocumentCreateElement("image"); nnSetAttribute("imageUrl", "jpg");  XmlNode node = xmlDocumentSelectSingleNode("content/section/page/gall/folder");//定位到folder節點 nodeAppendChild(nn);//附加新節點  //儲存 xmlDocumentSave("testxml"); 

2、用Linq to XML來解析

可以通過遍曆,來獲得你想要的節點的內容或屬性

XElement root = XElementLoad("testxml"); foreach (XAttribute att in rootAttributes()) {   rootAdd(new XElement(attName, (string)att)); } ConsoleWriteLine(root); 

3、附一個詳細點的例子

比如要解析如下的xml檔案,將其轉化為Ilist對象。

<?xml version="0" encoding="utf-8"?> <Car>  <carcost>   <ID>20130821133126</ID>   <uptime>60</uptime>   <downtime>30</downtime>   <price>4</price>  </carcost>  <carcost>   <ID>20130821014316</ID>   <uptime>120</uptime>   <downtime>60</downtime>   <price>3</price>  </carcost>  <carcost>   <ID>20130822043127</ID>   <uptime>30</uptime>   <downtime>0</downtime>   <price>5</price>  </carcost>  <carcost>   <ID>20130822043341</ID>   <uptime>120以上!</uptime>   <downtime>120</downtime>   <price>2</price>  </carcost> </Car> 

在控制台應用程式中輸入如下代碼即可。

class Program {   static void Main(string[] args)   {     IList<CarCost> resultList = new List<CarCost>();      XmlDocument xmlDocument = new XmlDocument();     xmlDocumentLoad("testxml");      XmlNodeList xmlNodeList = xmlDocumentSelectSingleNode("Car")ChildNodes;     foreach (XmlNode list in xmlNodeList)     {       CarCost carcost = new CarCost       (         listSelectSingleNode("ID")InnerText,         listSelectSingleNode("uptime")InnerText,         listSelectSingleNode("downtime")InnerText,         floatParse(listSelectSingleNode("price")InnerText)       );       resultListAdd(carcost);     }      IEnumerator enumerator = resultListGetEnumerator();     while (enumeratorMoveNext())     {       CarCost carCost = enumeratorCurrent as CarCost;       ConsoleWriteLine(carCostID + " " + carCostUpTime + " " + carCostDownTime + " " + carCostPrice);     }   } }  public class CarCost {   public CarCost(string id, string uptime, string downtime, float price)   {     thisID = id;     thisUpTime = uptime;     thisDownTime = downtime;     thisPrice = price;   }   public string ID { get; set; }   public string UpTime { get; set; }   public string DownTime { get; set; }   public float Price { get; set; } } 

二、C#對JSON格式資料的解析

引用NewtonsoftJsondll檔案,來解析。

比如:有個要解析的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 = JsonConvertDeserializeObject<List<JobInfo>>(json);         foreach (JobInfo jobInfo in jobInfoList)       {         ConsoleWriteLine("UserName:" + jobInfoUserName + "UserID:" + jobInfoUserID);       } 

這樣就可以正常輸出內容了。

我想肯定有人會問,如果有多層關係的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 = JsonConvertDeserializeObject<List<Info>>(json);  foreach (Info info in infoList) {   ConsoleWriteLine("id:" + infodataMID); } 

按照我們的預期,應該能夠得到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 = JsonConvertDeserializeObject<Data>(json);        foreach (var item in datadatabins)       {         //輸出:JTL-Z38001、JTL-Z38002,其它類似         ConsoleWriteLine(itemcode);       }     }   } 

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 = JsonConvertDeserializeObject<Data>(json);       ConsoleWriteLine(datadatamouldsbinRelease);//輸出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 = JsonConvertDeserializeObject<Data>(json);        foreach (var item in datadatabatchs)       {         ConsoleWriteLine(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; }   } } 

除了上述返回類的實體物件做法之外,JSONNET還提供了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)JsonConvertDeserializeObject(j);       ConsoleWriteLine(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; }   } } 

直接運行,返回結果如下:

如果輸出內容修改為:

ConsoleWriteLine(jo["data"]); 

繼續取bin節點。

ConsoleWriteLine(jo["data"]["bin"]); 

最後我們取其中name對應的value。

ConsoleWriteLine(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();       dataid = 1;       datavalue = "cate";       datachild = 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 = JsonConvertSerializeObject(data);       ConsoleWriteLine(json);        //還原序列化為對象       Data jsonData = JsonConvertDeserializeObject<Data>(json);     }   }    public class Data   {     public int id { get; set; }     public string value { get; set; }     public List<Data> child { get; set; }   } } 

我們驗證一下產生的結果:

JObject jo = (JObject)JsonConvertDeserializeObject(json); ConsoleWriteLine(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 = JsonConvertDeserializeObject<Data[]>(jsonString);        foreach (Data data in datas)       {         downList[] downList = datadownList;         line line = dataline;         upList[] upLists = dataupList;          //輸出         ConsoleWriteLine(stringJoin(",", lineId, lineName, lineicCard));         foreach (upList upList in upLists)         {           ConsoleWriteLine(stringJoin(",", upListendTime, upListstartTime, upListsId, upListsType));         }         ConsoleWriteLine("-----------------------------------------------");       }     }   }     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; }   } } 

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.