十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊
量身定制 + 運營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
C#對XML、JSON等格式的解析
目前創(chuàng)新互聯(lián)建站已為1000多家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)站空間、網(wǎng)站運營、企業(yè)網(wǎng)站設(shè)計、新源網(wǎng)站維護(hù)等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。一、C#對XML格式數(shù)據(jù)的解析
1、用XMLDocument來解析
XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load("test.xml"); //創(chuàng)建新節(jié)點 XmlElement nn = xmlDocument.CreateElement("p_w_picpath"); nn.SetAttribute("p_w_picpathUrl", "6.jpg"); XmlNode node = xmlDocument.SelectSingleNode("content/section/page/gall/folder");//定位到folder節(jié)點 node.AppendChild(nn);//附加新節(jié)點 //保存 xmlDocument.Save("test.xml");
2、用Linq to XML來解析
可以通過遍歷,來獲得你想要的節(jié)點的內(nèi)容或?qū)傩?/p>
XElement root = XElement.Load("test.xml"); foreach (XAttribute att in root.Attributes()) { root.Add(new XElement(att.Name, (string)att)); } Console.WriteLine(root);
3、附一個詳細(xì)點的例子
比如要解析如下的xml文件,將其轉(zhuǎn)化為Ilist對象。
20130821133126 60 30 0.4 20130821014316 120 60 0.3 20130822043127 30 0 0.5 20130822043341 120以上! 120 0.2
在控制臺應(yīng)用程序中輸入如下代碼即可。
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格式數(shù)據(jù)的解析
引用Newtonsoft.Json.dll文件,來解析。
比如:有個要解析的JSON字符串
[{"TaskRoleSpaces":"","TaskRoles":"","ProxyUserID":"5d9ad5dc1c5e494db1d1b4d8d79b60a7","UserID":"5d9ad5dc1c5e494db1d1b4d8d79b60a7","UserName":"姓名","UserSystemName":"2234","OperationName":"送合同負(fù)責(zé)人","OperationValue":"同意","OperationValueText":"","SignDate":"2013-06-19 10:31:26","Comment":"同意","FormDataHashCode":"","SignatureDivID":""},{"TaskRoleSpaces":"","TaskRoles":"","ProxyUserID":"2c96c3943826ea93013826eafe6d0089","UserID":"2c96c3943826ea93013826eafe6d0089","UserName":"姓名2","UserSystemName":"1234","OperationName":"送合同負(fù)責(zé)人","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函數(shù)內(nèi)部輸入如下代碼:
string json = @"[{'TaskRoleSpaces':'','TaskRoles':'','ProxyUserID':'5d9ad5dc1c5e494db1d1b4d8d79b60a7','UserID':'5d9ad5dc1c5e494db1d1b4d8d79b60a7','UserName':'姓名','UserSystemName':'2234','OperationName':'送合同負(fù)責(zé)人','OperationValue':'同意','OperationValueText':'','SignDate':'2013-06-19 10:31:26','Comment':'同意','FormDataHashCode':'','SignatureDivID':''},{'TaskRoleSpaces':'','TaskRoles':'','ProxyUserID':'2c96c3943826ea93013826eafe6d0089','UserID':'2c96c3943826ea93013826eafe6d0089','UserName':'姓名2','UserSystemName':'1234','OperationName':'送合同負(fù)責(zé)人','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); }
這樣就可以正常輸出內(nèi)容了。
我想肯定有人會問,如果有多層關(guān)系的json字符串該如何處理呢?沒關(guān)系,一樣的處理。
比如如何解析這個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); }
按照我們的預(yù)期,應(yīng)該能夠得到1019的結(jié)果。
截圖為證:
另外,對于有些json格式不是標(biāo)準(zhǔn)的,可以使用通用的方法進(jìn)行解析。
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下載地址:下載吧
創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務(wù)器,動態(tài)BGP最優(yōu)骨干路由自動選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨有T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動現(xiàn)已開啟,新人活動云服務(wù)器買多久送多久。