Deserialization XML to object with list in c#

2019-09-10 03:13发布

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>

1条回答
欢心
2楼-- · 2019-09-10 03:40

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; }
}
查看更多
登录 后发表回答