I have some XML from a third party that looks something like this:
<Breakfasts>
<Name>Cornflakes</Name>
<Description>Just add milk</Name>
<Name>Toast</Name>
<Name>Muesli</Name>
<Description>Healthy option</Description>
</Breakfasts>
We have to infer the relationship between Name and Description by the position of the nodes in the XML. So Cornflakes is "Just add milk", Toast does not have a description, Muesli is "Healthy option" and so on.
I have a class called Breakfast which looks like this:
public class Breakfast
{
public string Name { get; set; }
public string Description { get; set; }
}
How can this XML be parsed (using XDocument, perhaps?) into a List of Breakfast?
Ick - what a horrible format. I'd probably do something like:
var list = doc.Descendants("Name").Select(MakeBreakfast).ToList();
...
static Breakfast MakeBreakfast(XElement nameElement)
{
string name = (string) nameElement;
var nextElement = nameElement.ElementsAfterSelf().FirstOrDefault();
string description =
nextElement != null && nextElement.Name.LocalName == "Description"
? (string) nextElement
: null;
return new Breakfast { Name = name, Description = description };
}
See more on this question at Stackoverflow