服务器之家

服务器之家 > 正文

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

时间:2021-12-13 15:17     来源/作者:极简

一、c#对xml格式数据的解析

1、用xmldocument来解析

?
1
2
3
4
5
6
7
8
9
10
11
12
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来解析

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

?
1
2
3
4
5
6
xelement root = xelementload("testxml");
foreach (xattribute att in rootattributes())
{
  rootadd(new xelement(attname, (string)att));
}
consolewriteline(root);

3、附一个详细点的例子

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?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>

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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字符串

?
1
[{"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":""}]

首先定义个实体类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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函数内部输入如下代码:

?
1
2
3
4
5
6
7
8
9
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'}}]  ?

首先还是定义实体类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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方法里面,键入:

?
1
2
3
4
5
6
7
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}]}}

定义数据结构:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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函数:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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:

?
1
{\"success\":true,\"data\":{\"name\":\"张三\",\"moulds\":{\"stockimport\":true,\"stockexport\":true,\"justifylocation\":true,\"justifybin\":false,\"binrelease\":false}}}

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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:

?
1
2
3
4
5
6
7
8
9
10
11
12
{
  "success": true,
  "data": {
    "id": 100001,
    "bin": "jit-3js-2k",
    "targetbin": "jit-3js-3k",
    "batchs": [
      "b20140101",
      "b20140102"
    ]
  }
}

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

完整代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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类,可以取自己指定节点的内容。

比如:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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等格式的解析

如果输出内容修改为:

?
1
consolewriteline(jo["data"]);

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

继续取bin节点。

?
1
consolewriteline(jo["data"]["bin"]);

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

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

?
1
consolewriteline(jo["data"]["bin"]["name"]);

一步一步的获取了json字符串对应的value。

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
{
  "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这样的属性,可以无限循环下去,是个典型的树形结构。

完整的代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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; }
  }
}

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

?
1
2
jobject jo = (jobject)jsonconvertdeserializeobject(json);
consolewriteline(jo);

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
[
  {
    "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"
      }
    ]
  }
]
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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; }
  }
}

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

原文链接:http://blog.csdn.net/chinacsharper/article/details/9246627

标签:
JSON XML C# 

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部