I need to deserialize XML into one simple array of objects, but can't quite figure out how to do it. Here is my simplified XML:
<?xml version="1.0" encoding="Windows-1250"?>
<document>
<datasets>
<dataset0>
<rows>
<row>
<fields>
<id>1</id>
<name>Cat1</name>
</fields>
</row>
<row>
<fields>
<id>2</id>
<name>Cat2</name>
</fields>
</row>
</rows>
</dataset0>
</datasets>
</document>
I've created class for the object to deserialize into
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
And the deserialization code
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Category[]), new XmlRootAttribute("rows"));
using (FileStream myFileStream = categoryFile.OpenRead())
{
var categoryArray = (Category[])xmlSerializer.Deserialize(myFileStream);
}
This obviously doesn't work, I've tried various XmlElement and XmlRoot tags, but I don't quite know what I'm doing so I stripped all that out to avoid public embarrassment. Thanks for any input.
It seems that, the object which you want to deserialize doesn't have exact compatibility with your xml file. So, in this case it could be more flexible to use Linq to xml solution.
var xDocument = XDocument.Parse(xml);
var categoryList = xDocument.Descendants("fields").Select(x => new Category
{
Name = x.Element("name").Value,
Id = int.Parse(x.Element("id").Value)
});