2

我的课:

public class Device
{
     int ID;
     string Name;
     List<Function> Functions;
}

和类功能:

public class Function
{
     int Number;
     string Name;
}

我有这个结构的xml文件:

 <Devices>
   <Device Number="58" Name="Default Device" >
     <Functions>
         <Function Number="1" Name="Default func" />
         <Function Number="2" Name="Default func2" />
         <Function Number="..." Name="...." />
     </Functions>
   </Device>
 </Devices>

这是代码,我正在尝试读取对象:

  var list = from tmp in document.Element("Devices").Elements("Device")
                       select new Device()
                       {
                           ID = Convert.ToInt32(tmp.Attribute("Number").Value),
                           Name = tmp.Attribute("Name").Value,
                           //??????
                       };
            DevicesList.AddRange(list);

我如何阅读“功能”???

4

1 回答 1

7

再次做同样的事情,使用ElementsandSelect将一组元素投影到对象。

var list = document
     .Descendants("Device")
     .Select(x => new Device {
                     ID = (int) x.Attribute("Number"),
                     Name = (string) x.Attribute("Name"),
                     Functions = x.Element("Functions")
                                  .Elements("Function")
                                  .Select(f =>
                                      new Function {
                                      Number = (int) f.Attribute("Number"),
                                      Name = (string) f.Attribute("Name")
                                    }).ToList()
                  });

为了清楚起见,我实际上建议FromXElement在每个Device和中编写一个静态方法Function。然后每一位代码只能做一件事。例如,Device.FromXElement可能看起来像这样:

public static Device FromXElement(XElement element)
{
    return new Device
    {
        ID = (int) element.Attribute("Number"),
        Name = (string) element.Attribute("Name"),
        Functions = element.Element("Functions").Elements("Function")
                         .Select(Function.FromXElement)
                         .ToList();
    };
}

这也允许您在类中将设置器设为私有,因此它们可以是公开的不可变的(在集合周围需要一些努力)。

于 2012-08-06T18:15:32.043 回答