Deserialization XML to object with list in c#

三世轮回 提交于 2019-12-13 02:54:07

问题


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:


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; }
}


来源:https://stackoverflow.com/questions/25959912/deserialization-xml-to-object-with-list-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!