How to deserialize xml to object

user829174 picture user829174 · May 9, 2012 · Viewed 236.1k times · Source
<StepList>
  <Step>
    <Name>Name1</Name>
    <Desc>Desc1</Desc>
  </Step>
  <Step>
    <Name>Name2</Name>
    <Desc>Desc2</Desc>
  </Step>
</StepList>

I have this XML, How should i model the Class so i will be able to deserialize it using XmlSerializer object?

Answer

dknaack picture dknaack · May 9, 2012

Your classes should look like this

[XmlRoot("StepList")]
public class StepList
{
    [XmlElement("Step")]
    public List<Step> Steps { get; set; }
}

public class Step
{
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("Desc")]
    public string Desc { get; set; }
}

Here is my testcode.

string testData = @"<StepList>
                        <Step>
                            <Name>Name1</Name>
                            <Desc>Desc1</Desc>
                        </Step>
                        <Step>
                            <Name>Name2</Name>
                            <Desc>Desc2</Desc>
                        </Step>
                    </StepList>";

XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
    StepList result = (StepList) serializer.Deserialize(reader);
}

If you want to read a text file you should load the file into a FileStream and deserialize this.

using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open)) 
{
    StepList result = (StepList) serializer.Deserialize(fileStream);
}