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

822 Views Asked by At

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 ?

2

There are 2 best solutions below

0
On BEST ANSWER

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()
    { }
} 
0
On

Add the root yourself like this:

XmlRootAttribute root = new XmlRootAttribute();
root.ElementName = "delivery";
// root.Namespace = "http://www.whatever.com";
root.IsNullable = true;

// your code goes below