温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-05-30 08:19:25 来源:网络 阅读:7589 作者:guwei4037 栏目:编程语言

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的结果。


截图为证:

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

另外,对于有些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下载地址:下载吧

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI