C# 使用Linq从XML文件读取INT列表
我有一个以下XML文件:C# 使用Linq从XML文件读取INT列表,c#,xml,linq,C#,Xml,Linq,我有一个以下XML文件: <Application> <Items> <Item> <Id>0</Id> <StartDate>0001-01-11T00:00:00</StartDate> <EndDate>0001-01-30T00:00:00</EndDate> <ItemType>0</ItemType>
<Application>
<Items>
<Item>
<Id>0</Id>
<StartDate>0001-01-11T00:00:00</StartDate>
<EndDate>0001-01-30T00:00:00</EndDate>
<ItemType>0</ItemType>
<Comments>fgdfg</Comments>
<SelectedIds>
<Id>108</Id>
<Id>110</Id>
<Id>111</Id>
</SelectedIds>
</Item>
</Items>
0
0001-01-11T00:00:00
0001-01-30T00:00:00
0
fgdfg
108
110
111
我想阅读代表我的CustomClass的项目列表。我正在使用以下linq查询:
CustomClassList = new ObservableCollection<CustomClass>((from r in xml.Descendants("Application").Descendants("Items").Descendants("Item")
select (new CustomClass()
{
Id = (int)r.Element("Id"),
StartDate= DateTime.Parse(r.Element("StartDate").Value),
EndDate = DateTime.Parse(r.Element("EndDate").Value),
ItemType = (ItemType)byte.Parse(r.Element("ItemType").Value),
Comment = r.Element("Comment").Value,
SelectedIds = new List<int>((from p in xml.Descendants("Application").Descendants("Items").Descendants("Item").Descendants("SelectedIds")
select (int)p.Element("Id")).ToList())
})).ToList());
CustomClassList=newobserveCollection((来自xml.substands(“应用程序”).substands(“项目”).substands(“项目”)中的r)
选择(新建CustomClass()
{
Id=(int)r.Element(“Id”),
StartDate=DateTime.Parse(r.Element(“StartDate”).Value),
EndDate=DateTime.Parse(r.Element(“EndDate”).Value),
ItemType=(ItemType)byte.Parse(r.Element(“ItemType”).Value),
注释=r.元素(“注释”).值,
SelectedIds=新列表((从xml.substands(“应用程序”).substands(“项目”).substands(“项目”).substands(“SelectedIds”)中的p)
选择(int)p.Element(“Id”).ToList()
})).ToList());
它可以正常工作,只是SelectedIds只包含XML中的第一个Id,而不是所有Id。您应该使用
r
作为子列表的起点,而不是“全局”根XML
:
SelectedIds = r.Descendants("SelectedIds")
.SelectMany(p => p.Descendants("Id").Select(x => (int)x))
.ToList()