C#对XML、JSON等格式的解析-创新互联
C#对XML、JSON等格式的解析
目前创新互联建站已为1000多家的企业提供了网站建设、域名、网站空间、网站运营、企业网站设计、新源网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。一、C#对XML格式数据的解析
1、用XMLDocument来解析
XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load("test.xml"); //创建新节点 XmlElement nn = xmlDocument.CreateElement("p_w_picpath"); nn.SetAttribute("p_w_picpathUrl", "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 in root.Attributes()) { root.Add(new XElement(att.Name, (string)att)); } Console.WriteLine(root);
3、附一个详细点的例子
比如要解析如下的xml文件,将其转化为Ilist对象。
20130821133126 60 30 0.4 20130821014316 120 60 0.3 20130822043127 30 0 0.5 20130822043341 120以上! 120 0.2
在控制台应用程序中输入如下代码即可。
class Program { static void Main(string[] args) { IListresultList = new List (); 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 { 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 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':''}] "; ListjobInfoList = JsonConvert.DeserializeObject >(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'}}] ?
首先还是定义实体类:
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'}}]"; ListinfoList = JsonConvert.DeserializeObject >(json); foreach (Info info in infoList) { Console.WriteLine("id:" + info.data.MID); }
按照我们的预期,应该能够得到1019的结果。
截图为证:
另外,对于有些json格式不是标准的,可以使用通用的方法进行解析。
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下载地址:下载吧
创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。
新闻标题:C#对XML、JSON等格式的解析-创新互联
链接URL:http://azwzsj.com/article/csoipi.html