LINQ-读取xml到对象列表 [英] LINQ-Reading xml to object list
本文介绍了LINQ-读取xml到对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<?xml version="1.0" encoding="utf-8" ?>
<reportgroups>
<Reportgroup id="1" name="reportGroup1">
<report id="1" name="report1" isSheduled="false"></report>
<report id="2" name="report2" isSheduled="false"></report>
<report id="3" name="report3" isSheduled="false"></report>
</Reportgroup>
<Reportgroup id="2" name="reportGrouop2">
<report id="4" name="report4" isSheduled="false"></report>
</Reportgroup>
<Reportgroup id="3" name="reportGrouop3"></Reportgroup>
</reportgroups>
我有课
public class Reportgroup
{
public int id { get; set; }
public string name { get; set; }
}
public class Report
{
public int id { get; set; }
public string name { get; set; }
public bool isSheduled { get; set; }
}
我如何使用linq将这个xml读取到Reportgroup对象的列表中. 它的语法是什么. 报告组列表中的每个项目都应包含报告列表
how can i read this xml to a list of Reportgroup object using linq. What is its syntax. Each item in List of Reportgroup should contain list of Report
推荐答案
您的Reportgroup
类似乎缺少与Report
关联的方法.无论如何,您可以这样阅读(对您的班级进行一些调整):
Your Reportgroup
class seems to be missing a way to associate with the Report
s. Anyway, you can read it like this (with a few tweaks to your classes):
public class ReportGroup // CamelCase!!!
{
public int Id { get; set; }
public string Name { get; set; }
public List<Report> Reports { get; set; } // need to hold the associated reports
}
public class Report
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSheduled { get; set; }
}
var doc = XDocument.Load("path/to/file.xml");
var reportGroups = doc.Element("reportgroups")
.Elements("Reportgroup")
.Select(rg => new ReportGroup
{
Id = (int)rg.Attribute("id"),
Name = (string)rg.Attribute("name"),
Reports = rg.Elements("report")
.Select(r => new Report
{
Id = (int)r.Attribute("id"),
Name = (string)r.Attribute("name"),
IsScheduled = (bool)r.Attribute("isScheduled"),
}).ToList();
}).ToList();
这篇关于LINQ-读取xml到对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文