6

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>
user829174
  • 6,132
  • 24
  • 75
  • 125

3 Answers3

14
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.

Umair
  • 3,063
  • 1
  • 29
  • 50
4

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

Ocelot20
  • 10,510
  • 11
  • 55
  • 96
1

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
});
Sharpiro
  • 2,305
  • 2
  • 18
  • 27