LINQ的XML对象 - 如何填充集合<富> [英] Linq xml to object - How to populate a Collection<foo>
本文介绍了LINQ的XML对象 - 如何填充集合<富>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要阅读一些XML和填充我的阶级结构。我会很高兴,如果有人可以给我提供了一些整洁的代码
I need to read some xml and populate my class-structure. I would be so happy if somebody could provide me some neat code for that.
我的简化的类结构:
public class Event
{
[XmlAttribute("Id")]
public string Id { get; set; }
[XmlElement("StartTimes")]
public Collection<StartTime> StartTimeCollection;
}
public class StartTime
{
[XmlAttribute("Time")]
public string Start { get; set; }
[XmlAttribute("Mon")]
public bool Monday { get; set; }
[XmlAttribute("Tue")]
public bool Tuesday { get; set; }
[XmlAttribute("Wed")]
public bool Wednesday { get; set; }
[XmlAttribute("Thu")]
public bool Thursday { get; set; }
[XmlAttribute("Fri")]
public bool Friday { get; set; }
[XmlAttribute("Sat")]
public bool Saturday { get; set; }
[XmlAttribute("Sun")]
public bool Sunday { get; set; }
}
XML如下:
<Event Id="f7cfc3a5-5b1b-4941-8d7b-f8a4a71fa530">
<StartTimes>
<StartTime Time="19:00" Mon="false" Tue="false" Wed="false" Thu="false" Fri="true" Sat="false" Son="false"/>
</StartTimes>
</Event>
这就是我的LINQ声明的样子:
And that's how my linq statement looks like:
from x in doc.Descendants("Event")
select new Event()
{
Id = x.Attribute("Id").Value,
StartTimeCollection = x.Descendants("StartTimes") ????????? <-- That's the tricky part for me
}
问候
Regards
推荐答案
由于收藏< T>
暴露出的构造接受一个的IList< T>
,您可以使用的SelectMany()并写:
Since Collection<T>
exposes a constructor that takes an IList<T>
, you can use SelectMany() and write:
from x in doc.Descendants("Event")
select new Event() {
Id = x.Attribute("Id").Value,
StartTimeCollection = new Collection<StartTime>(
x.Descendants("StartTimes").SelectMany(
startTimes => startTimes.Elements("StartTime").Select(
startTime => new StartTime() {
Start = startTime.Attribute("Time").Value,
Monday = Boolean.Parse(startTime.Attribute("Mon").Value),
Tuesday = Boolean.Parse(startTime.Attribute("Tue").Value),
Wednesday = Boolean.Parse(startTime.Attribute("Wed").Value),
Thursday = Boolean.Parse(startTime.Attribute("Thu").Value),
Friday = Boolean.Parse(startTime.Attribute("Fri").Value),
Saturday = Boolean.Parse(startTime.Attribute("Sat").Value),
Sunday = Boolean.Parse(startTime.Attribute("Son").Value)
})).ToList())
}
请注意,我用属性(儿子)
而不是属性(太阳报)
来初始化周日
属性,因为属性被命名一样,在您的标记。这可能是一个错字,但。
Note that I used Attribute("Son")
instead of Attribute("Sun")
to initialize the Sunday
property, since the attribute is named like that in your markup. It might be a typo, though.
这篇关于LINQ的XML对象 - 如何填充集合<富>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文