Sunday, 21 September 2014

Deserialization XML to object with list in c#



I want to deserialize XML to object in C#, object has one string property and list of other objects. There are classes which describe XML object, my code doesn't work (it is below, XML is at end of my post). My Deserialize code doesn't return any object.


I think I do something wrong with attributes, could you check it and give me some advice to fix it. Thanks for your help.



[XmlRoot("shepherd")]
public class Shepherd
{
[XmlElement("name")]
public string Name { get; set; }

[XmlArray(ElementName = "sheeps", IsNullable = true)]
[XmlArrayItem(ElementName = "sheep")]
public List<Sheep> Sheeps { get; set; }
}

public class Sheep
{
[XmlElement("colour")]
public string colour { get; set; }
}


There is C# code to deserialize XML to objects



var rootNode = new XmlRootAttribute();
rootNode.ElementName = "createShepherdRequest";
rootNode.Namespace = "http://ift.tt/1rLzZki";
rootNode.IsNullable = true;

Type deserializeType = typeof(Shepherd[]);
var serializer = new XmlSerializer(deserializeType, rootNode);

using (Stream xmlStream = new MemoryStream())
{
doc.Save(xmlStream);

var result = serializer.Deserialize(xmlStream);
return result as Shepherd[];
}


There is XML example which I want to deserialize



<?xml version="1.0" encoding="utf-8"?>
<createShepherdRequest xmlns="http://ift.tt/1rLzZki">
<shepherd>
<name>name1</name>
<sheeps>
<sheep>
<colour>colour1</colour>
</sheep>
<sheep>
<colour>colour2</colour>
</sheep>
<sheep>
<colour>colour3</colour>
</sheep>
</sheeps>
</shepherd>
</createShepherdRequest>

No comments:

Post a Comment