2

我需要阅读一些 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
}

问候

4

1 回答 1

2

由于Collection<T>公开了一个采用的构造函数IList<T>,因此您可以使用SelectMany()并编写:

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属性,因为该属性的名称与您的标记中的名称类似。不过,这可能是一个错字。

于 2013-03-06T09:31:50.650 回答