Linq xml to object - 如何填充Collection <foo> </foo>

时间:2013-03-06 08:52:39

标签: c# linq

我需要阅读一些xml并填充我的类结构。如果有人能为我提供一些简洁的代码,我会很高兴。

我简化的班级结构:

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语句的样子:

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
}

此致

1 个答案:

答案 0 :(得分:2)

由于Collection<T>公开了IList<T>的{​​{3}},您可以使用constructor并写一下:

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())
}

请注意,我使用Attribute("Son")而不是Attribute("Sun")来初始化Sunday属性,因为该属性的名称与标记中的属性相同。不过,这可能是一个错字。