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

Elementsと を使用しSelectて、一連の要素をオブジェクトに射影して、同じことをもう一度行います。

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のそれぞれに静的メソッドを記述することをお勧めします。その後、コードの各ビットは 1 つのことだけを実行できます。たとえば、次のようになります。DeviceFunctionDevice.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 に答える