2

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.

1 Answer 1

2

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)
});
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't even consider Linq, I guess no problem using that instead, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.