欢迎来到入门教程网!

C#教程

当前位置:主页 > 软件编程 > C#教程 >

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

来源:本站原创|时间:2020-01-10|栏目:C#教程|点击:

一、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; } 
  } 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

上一篇:C#对多个集合和数组的操作方法(合并,去重,判断)

栏    目:C#教程

下一篇:c# 两个数组比较,将重复部分去掉,返回不重复部分的实现

本文标题:详解C#对XML、JSON等格式的解析

本文地址:https://www.xiuzhanwang.com/a1/C_jiaocheng/6102.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有