Search code examples
c#xmlxml-deserialization

deserialize a string (xml node like syntax) to c# object


I am trying to deserialize a string to object. Is xml node like syntax, but is not an xml (as there is no root node or namespace). This is what I have so far, having this error:

<delivery xmlns=''>. was not expected

Deserialize code:

var number = 2;
var amount = 3;
var xmlCommand = $"<delivery number=\"{number}\" amount=\"{amount}\" />";
XmlSerializer serializer = new XmlSerializer(typeof(Delivery));
var rdr = new StringReader(xmlCommand);
Delivery delivery = (Delivery)serializer.Deserialize(rdr);

Delivery object:

using System.Xml.Serialization;

namespace SOMWClient.Events
{
    public class Delivery
    {
        [XmlAttribute(AttributeName = "number")]
        public int Number { get; set; }

        [XmlAttribute(AttributeName = "amount")]
        public string Amount { get; set; }

        public Delivery()
        {

        }
    }
}

How can I avoid the xmlns error when deserializing ?


Solution

  • Change the Delivery class and add information about the root element (XmlRoot attribute):

    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [XmlRoot("delivery")]
    public class Delivery
    {
        [XmlAttribute(AttributeName = "number")]
        public int Number { get; set; }
    
        [XmlAttribute(AttributeName = "amount")]
        public string Amount { get; set; }
    
        public Delivery()
        { }
    }