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

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

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

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

1、用XMLDocument来解析

 XmlDocument xmlDocument = newXmlDocument();
 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来解析

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

            XElement root = XElement.Load("test.xml");
            foreach (XAttribute att inroot.Attributes())
            {
                root.Add(new XElement(att.Name, (string)att));
            }
            Console.WriteLine(root);

3、附一个详细点的例子

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

<?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>

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

    classProgram
    {
        static void Main(string[] args)
        {
            IList<CarCost> resultList = new List<CarCost>();

            XmlDocument xmlDocument = newXmlDocument();
            xmlDocument.Load("test.xml");

            XmlNodeList xmlNodeList = xmlDocument.SelectSingleNode("Car").ChildNodes;
            foreach (XmlNode list inxmlNodeList)
            {
                CarCost carcost = newCarCost
                (
                    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 asCarCost;
                Console.WriteLine(carCost.ID + " " + carCost.UpTime + " " + carCost.DownTime + " " +carCost.Price);
            }
        }
    }

    public classCarCost
    {
        public CarCost(string id, string uptime, string downtime, floatprice)
        {
            this.ID =id;
            this.UpTime =uptime;
            this.DownTime =downtime;
            this.Price =price;
        }
        public string ID { get; set; }
        public string UpTime { get; set; }
        public string DownTime { get; set; }
        public float Price { get; set; }
    }

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

首先定义个实体类:

    public classJobInfo
    {
        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 = JsonConvert.DeserializeObject<List<JobInfo>>(json);
 
            foreach (JobInfo jobInfo injobInfoList)
            {
                Console.WriteLine("UserName:" + jobInfo.UserName + "UserID:" +jobInfo.UserID);
            }

这样就可以正常输出内容了。

我想肯定有人会问,如果有多层关系的json字符串该如何处理呢?没关系,一样的处理。

比如如何解析这个json字符串:[{'phantom':true,'id':'20130717001','data':{'MID':1019,'Name':'aaccccc','Des':'cc','Disable':'启用','Remark':'cccc'}}] ?

首先还是定义实体类:

    public classInfo
    {
        public string phantom { get; set; }
        public string id { get; set; }
        public data data { get; set; }
    }

    public classdata
    {
        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 = JsonConvert.DeserializeObject<List<Info>>(json);

            foreach (Info info ininfoList)
            {
                Console.WriteLine("id:" +info.data.MID);
            }

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

截图为证:

C#对XML、JSON等格式的解析 (转)第1张

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

            string jsonText = @"{'Count':1543,'Items':[{'UnitID':6119,'UnitName':'C'}]}";
            JsonReader reader = new JsonTextReader(newStringReader(jsonText));
            while(reader.Read())
            {
                Console.WriteLine(reader.TokenType + "" + reader.ValueType + "" +reader.Value);
            }

免责声明:文章转载自《C#对XML、JSON等格式的解析 (转)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇cocos2dx实现功能强大的RichText控件Java8 stream.sort 多字段排序下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

60个数据窗口技巧(转)

  60个数据窗口技巧 1.如何让存储文件目录的列,显示图片? 答:选择对应的column的display as picture属性为true 2、如何复制grid类型的所选择的行的数据到系统剪切板?答:string ls_selectedls_selected=dw_1.Object.DataWindow.Selected.Dataclipboard(...

Python心得基础篇【5】模块

模块,用一砣代码实现了某个功能的代码集合。  类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。 如:os 是系统相关的模块;file是文件操作相关的模块 模块分为三...

关于jabber协议

转:顺风飞扬 路是走出来的,http://blog.csdn.net/kunp/article/details/30465 1. 介绍     Jabber是一个由开源社区发起并领导开发的即时消息和在线状态的系统。Jabber系统和其它即时消息(IM)服务的一个功能上的差别在于Jabber拥有开放的XML协议。在保持Jabber1.0版本有关消息核心以及在...

深入剖析PHP输入流 php://input

另附一个一个连接: http://www.nowamagic.net/academy/detail/12220520 ///////////////////////////////////////////////////////////////另一种解释////////////////////////////////////////////////////...

Python基础-5

目录 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 hashlib re正则表达式 模块分为三种: 自定义模块 内置标准模块(又称标准库) 开源模块 自定义模块 和开源模块的使用参考 http://www.cnblogs.com/wupe...

(转)SQL对Xml字段的操作

T-Sql操作Xml数据 一、前言 SQL Server 2005 引入了一种称为 XML 的本机数据类型。用户可以创建这样的表,它在关系列之外还有一个或多个 XML 类型的列;此外,还允许带有变量和参数。为了更好地支持 XML 模型特征(例如文档顺序和递归结构),XML 值以内部格式存储为大型二进制对象 (BLOB)。 用户将一个XML数据存入数据库的时...