2012-08-06 83 views
2

我的類:讀取XML用的XDocument

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); 

我怎麼能讀「功能」 ???

+1

隨着你的'Devices'做的一樣嗎? – Schaliasos 2012-08-06 18:15:08

回答

7

再次做同樣的事情,使用ElementsSelect投射一組元素的對象。

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

爲清楚起見,其實我建議寫在每個DeviceFunction靜態FromXElement方法。然後每一段代碼都可以做一件事。因此,例如,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(); 
    }; 
} 

這也使您可以在setter方法的類內私有的,所以他們可以(有一點努力周圍的集合)公開不變。

+0

感謝我們再次,我會盡量 – 2012-08-06 18:21:48

+0

@喬恩你的意思是「功能」而不是「設備」 – Les 2012-08-06 18:50:26

+0

@Les,這並不重要,我意識到) – 2012-08-06 19:28:08