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

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

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

1、用XMLDocument来解析

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

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

1
2
3
4
5
6
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对象。

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="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>

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

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();
        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 { getset; }
    public string UpTime { getset; }
    public string DownTime { getset; }
    public float Price { getset; }
}

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

首先定义个实体类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class JobInfo
{
    public string TaskRoleSpaces { getset; }
    public string TaskRoles { getset; }
    public string ProxyUserID { getset; }
    public string UserID { getset; }
    public string UserName { getset; }
    public string UserSystemName { getset; }
    public string OperationName { getset; }
    public string OperationValue { getset; }
    public string OperationValueText { getset; }
    public DateTime SignDate { getset; }
    public string Comment { getset; }
    public string FormDataHashCode { getset; }
    public string SignatureDivID { getset; }
}

然后在控制台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 = 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'}}]  ?

首先还是定义实体类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Info
{
    public string phantom { getset; }
    public string id { getset; }
    public data data { getset; }
}
                  
public class data
{
    public int MID { getset; }
    public string Name { getset; }
    public string Des { getset; }
    public string Disable { getset; }
    public string Remark { getset; }
}

然后在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 = JsonConvert.DeserializeObject<List<Info>>(json);
             
foreach (Info info in infoList)
{
    Console.WriteLine("id:" + info.data.MID);
}

   按照我们的预期,应该能够得到1019的结果。


截图为证:

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

另外,对于有些json格式不是标准的,可以使用通用的方法进行解析。

1
2
3
4
5
6
string jsonText = @" {'Count':1543,'Items':[{'UnitID':6119,'UnitName':'C'}]}";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
while (reader.Read())
{
    Console.WriteLine(reader.TokenType + "\t\t" + reader.ValueType + "\t\t" + reader.Value);
}

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



本文转自 guwei4037  51CTO博客,原文链接:http://blog.51cto.com/csharper/1344190

上一篇:net core 小坑杂记之配置文件读取(不定期更新)


下一篇:数据透视表计算字段应用