Reputation: 165
My class:
public class Device
{
int ID;
string Name;
List<Function> Functions;
}
And Class Function:
public class Function
{
int Number;
string Name;
}
And i have xml file of this structure:
<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>
Here is the code, where i'm trying to read objects:
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);
how i can read "Functions"???
Upvotes: 2
Views: 503
Reputation: 1504172
Do the same thing again, using Elements
and Select
to project a set of elements to objects.
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()
});
For clarity, I'd actually suggest writing a static FromXElement
method in each of Device
and Function
. Then each bit of code can just do one thing. So for example, Device.FromXElement
might look like this:
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();
};
}
This also allows you to make the setters private within the classes, so they can be publicly immutable (with a bit of effort around the collections).
Upvotes: 7