Jacek
Jacek

Reputation: 12053

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://www.sheeps.pl/webapi/1_0";
        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://www.sheeps.pl/webapi/1_0">
  <shepherd>
    <name>name1</name>
    <sheeps>
      <sheep>
        <colour>colour1</colour>
      </sheep>
      <sheep>
        <colour>colour2</colour>
      </sheep>
      <sheep>
        <colour>colour3</colour>
      </sheep>
    </sheeps>
  </shepherd>
</createShepherdRequest>

Upvotes: 0

Views: 641

Answers (1)

Markus Jarderot
Markus Jarderot

Reputation: 89241

XmlRootAttribute does not change the name of the tag when used as an item. The serializer expects <Shepherd>, but finds <shepherd> instead. (XmlAttributeOverrides does not seem to work on arrays either.) One way to to fix it, is by changing the case of the class-name itself:

public class shepherd
{
    // ...
}

An easier alternative to juggling with attributes, is to create a proper wrapper class:

[XmlRoot("createShepherdRequest", Namespace = "http://www.sheeps.pl/webapi/1_0")]
public class CreateShepherdRequest
{
    [XmlElement("shepherd")]
    public Shepherd Shepherd { get; set; }
}

Upvotes: 1

Related Questions