I have an XML doc:
<statuses>
<status>
</status>
<status>
</status>
</statuses>
I have parsed this into an XDocument, and want to use LINQ to select the elements into a strongly typed collection of Status classes (all status elements are simple types, either string or int).
Any ideas how I can do this?
Thanks!
,
With XDocument
, something like below:
class Status
{
public int Id { get; set; }
public string Text { get; set; }
}
static void Main()
{
string xml = @"<xml>
<status id='1'><text>abcdef</text></status>
<status id='2'><text>ghijkl</text></status>
<status id='3'><text>mnopqr</text></status></xml>";
XDocument doc = XDocument.Parse(xml);
var list = (from el in doc.Root.Elements("status")
select new Status
{
Id = (int)el.Attribute("id"),
Text = (string)el.Element("text")
}).ToList();
}
Note that XmlSerializer
would also be a possibility here – reducing the amount of code you need to write and maintain.