国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

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

2019-10-29 21:17:50
字體:
來源:轉載
供稿:網友

一、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的結果。

截圖為證:

c#,解析xml,json解析

再附一個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; }   } } 

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

c#,解析xml,json解析

如果輸出內容修改為:

ConsoleWriteLine(jo["data"]); 

c#,解析xml,json解析

繼續取bin節點。

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

c#,解析xml,json解析

最后我們取其中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); 

c#,解析xml,json解析

再來一個復雜點的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; }   } } 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到c#教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 翼城县| 孙吴县| 清徐县| 鹤庆县| 东安县| 花莲市| 丹棱县| 乐安县| 乌海市| 荆门市| 南城县| 金华市| 井研县| 临西县| 武宣县| 比如县| 遂川县| 墨脱县| 靖江市| 方正县| 新宾| 凌云县| 都安| 邹平县| 宁夏| 监利县| 长阳| 利辛县| 武邑县| 华池县| 元阳县| 象州县| 襄垣县| 安西县| 元江| 新宁县| 浠水县| 岳阳市| 曲麻莱县| 卢湾区| 大连市|