How can i deserialize this xml using Linq?
I want to create List<Step>
<MySteps>
<Step>
<ID>1</ID>
<Name>Step 1</Name>
<Description>Step 1 Description</Description>
</Step>
<Step>
<ID>2</ID>
<Name>Step 2</Name>
<Description>Step 2 Description</Description>
</Step>
<Step>
<ID>3</ID>
<Name>Step 3</Name>
<Description>Step 3 Description</Description>
</Step>
<Step>
<ID>4</ID>
<Name>Step 4</Name>
<Description>Step 4 Description</Description>
</Step>
</MySteps>
string xml = @"<MySteps>
<Step>
<ID>1</ID>
<Name>Step 1</Name>
<Description>Step 1 Description</Description>
</Step>
<Step>
<ID>2</ID>
<Name>Step 2</Name>
<Description>Step 2 Description</Description>
</Step>
<Step>
<ID>3</ID>
<Name>Step 3</Name>
<Description>Step 3 Description</Description>
</Step>
<Step>
<ID>4</ID>
<Name>Step 4</Name>
<Description>Step 4 Description</Description>
</Step>
</MySteps>";
XDocument doc = XDocument.Parse(xml);
var mySteps = (from s in doc.Descendants("Step")
select new
{
Id = int.Parse(s.Element("ID").Value),
Name = s.Element("Name").Value,
Description = s.Element("Description").Value
}).ToList();
Heres how you would do it using LINQ. Obviously you should be doing your own error checking.
LINQ-to-XML is your answer.
List<Step> steps = (from step in xml.Elements("Step")
select new Step()
{
Id = (int)step.Element("Id"),
Name = (string)step.Element("Name"),
Description = (string)step.Element("Description")
}).ToList();
And a bit about doing the conversions from XML from Scott Hanselman
Showing the above answers in LINQ method syntax
Descendants:
var steps = xml.Descendants("Step").Select(step => new
{
Id = (int)step.Element("ID"),
Name = step.Element("Name").Value,
Description = step.Element("Description").Value
});
Elements:
var steps2 = xml.Element("MySteps").Elements("Step").Select(step => new
{
Id = (int)step.Element("ID"),
Name = step.Element("Name").Value,
Description = step.Element("Description").Value
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With