您好,登錄后才能下訂單哦!
C#對XML、JSON等格式的解析
一、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對象。
<?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>
在控制臺應用程序中輸入如下代碼即可。
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 { 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':''}] "; 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'}}] ?
首先還是定義實體類:
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 = JsonConvert.DeserializeObject<List<Info>>(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下載地址:下載吧
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。