Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing xml to object causes an error

Tags:

c#

xml

<?xml version="1.0" encoding="UTF-8"?>
<Order xmlns="urn:schemas-alibaba-com:billing-data" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
   <Currency>USD</Currency>
   <Description>description</Description>
</Order>

I have the above xml string that I am trying to deserialize to an object. This is an auto generated class.

[XmlTypeAttribute(AnonymousType = true,
                  Namespace = "urn:schemas-alibaba-com:billing-data")]
[XmlRootAttribute(ElementName="Order",
                  Namespace = "urn:schemas-alibaba-com:billing-data",
                  IsNullable = false)]
public partial class Order
{
    private string currencyField;

    private object descriptionField;
}

I am getting an exception:

Exception:    
{"There is an error in XML document (1, 2)."}  
Inner exception :
{"<Order xmlns='urn:schemas-alibaba-com:billing-data'> was not expected."}  

What am I missing here? Below is the code to deserialize: line 3 throws the exception.

var xmlReader = new StringReader(xml_data);
var serializer = new XmlSerializer(typeof(Order));    
var instance = (Order)serializer.Deserialize(xmlReader);
like image 397
keeda Avatar asked Apr 26 '26 17:04

keeda


1 Answers

I test your xml content, that is ok.

Here is my code:

[TestMethod]
public void Xml_ShouldBeDeserialized()
{
    var serializer = new XmlSerializer(typeof (Order));
    using (var stream = File.OpenRead(@"D:\test.xml"))
    {
        var obj = serializer.Deserialize(stream);
        var order = obj as Order;
        Assert.IsNotNull(order);                
    }
}

[XmlTypeAttribute(AnonymousType = true,
              Namespace = "urn:schemas-alibaba-com:billing-data")]
[XmlRoot(ElementName = "Order",
                  Namespace = "urn:schemas-alibaba-com:billing-data",
                  IsNullable = false)]
public partial class Order
{
    private string currencyField;

    private object descriptionField;

    public string Currency { get; set; }

    public string Description { get; set; }
}

I guess you might miss fields "Currency" and "Description", and they should be accessable,

like image 61
Teddy Avatar answered Apr 28 '26 07:04

Teddy