<Fruit>
<Apple>
<Pear>dar</Pear>
<Orange/>
<Starfruit>har</Starfruit>
</Apple>
<Lemon>
<Melon>yar</Melon>
<Lime>blah</Lime>
</Lemon>
<Fruit>
At the moment I have two select statements and then storing the values from those two separate enumerations into an object.
var myfruits = from myfruit in document.Descendants("UserAccount")
select new
{
Pear= myfruit.Element("Pear").Value,
Starfruit= myfruit.Element("Starfruit").Value,
};
var myfruits2 = from myfruit2 in document.Descendants("Product")
select new
{
Melon= myfruit2.Element("Melon").Value,
Lime= myfruit2.Element("Lime").Value,
};
foreach (var myfruit in myfruits)
{
megafruit.Pear=myfruit.Pear;
megafruit.Starfruit=myfruit.Starfruit;
}
foreach (var myfruit2 in myfruits2)
{
megafruit.Melon= myfruit2.Melon;
megafruit.Lime= myfruit2.Lime;
}
return megafruit;
You can navigate the XML document when you expand the query results (since you have a collection of all the descendant nodes). Something like this:
This will generate an anonymous class that has the properties filled with the values of the supplied XML. Alternatively, you can also use select new Megafruit() rather than just select new – which would create a new instance of the Megafruit class with the properties set according to the XML.
Note that this is a very simple example, assuming one occurrence of each of the fruits – it’s similiar to something I did at work many moons ago, where I knew the data I was getting was not going to be a collection (like a collection fo pears, or oranges, or whatever) so I coudl use SingleOrDefault.