Search code examples
c#xmlserializer

How to serialize / deserialize xml into a C# object?


How can I serialize / deserialize this xml string into a C# object?

<Response>
    <Business Number="99696" Name="My business" Address=""  />
    <Purchase PurchaseID="7" CustomerID="0" >
        <Item Name="item 1" Qty="100" UnitCost="10.0000" />
        <Item Name="item2" Qty="200" UnitCost="20.0000" />
    </Purchase>
</Response>

Thank you rubenc

I think is a different question because all the questions normally talk about one level and or a list of items

My problem is that I have different levels:

<Response>               //root
    <Business ... />     //level 1
    <Purchase... >       //level 1
        <Item ... />     // list

I get null in number, name etc.

This is what I have tried so far:

    [Serializable, XmlRoot("Response")]
    public class Response
    {
        public Depot depot = new Depot();

        // I have tried this also:
        //[XmlElement("Number")]
        //public string Number { get; set; }

        //[XmlElement("Name")]
        //public string Name { get; set; }
    }

    public class Depot
    {
        [XmlElement("Number")]
        public string Number { get; set; }

        [XmlElement("Name")]
        public string Name { get; set; }
    }


    static object DeserializeResponse(string responseString)
    {
        var serializer = new XmlSerializer(typeof(Response));

        Response result;
        using (var reader = new StringReader(responseString))
        {
            result = (Response)serializer.Deserialize(reader);
        }

        return result;
    }

Solution

  • I Found the solution:

    public class Response
    {
        [System.Xml.Serialization.XmlElementAttribute("Business", typeof(ResponseBusiness), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public object[] Items { get; set; }
    }
    
    public partial class ResponseBusiness
    {
        string NumberField;
    
        string NameField;
    
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Number
        {
            get
            {
                return this.NumberField;
            }
            set
            {
                this.NumberField = value;
            }
        }
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Name
        {
            get
            {
                return this.NameField;
            }
            set
            {
                this.NameField = value;
            }
        }
    

    I call the XmlSerializer class like this:

    var serializer = new XmlSerializer(typeof(Response), new XmlRootAttribute("Response"));
    

    And I can read the information like this:

    string businessNumber = ((ResponseBusiness)result.Items[0]).Number;

    Hope it can help someone else.