将xml反序列化为对象会导致错误

时间:2014-12-16 03:52:53

标签: 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>

我有上面的xml字符串,我试图反序列化为一个对象。这是一个自动生成的类。

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

我得到一个例外:

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

我在这里缺少什么?下面是反序列化的代码:第3行抛出异常。

var xmlReader = new StringReader(xml_data);
var serializer = new XmlSerializer(typeof(Order));    
var instance = (Order)serializer.Deserialize(xmlReader);

1 个答案:

答案 0 :(得分:2)

我测试你的xml内容,没关系。

这是我的代码:

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

我猜你可能会错过字段“货币”和“描述”,它们应该是可访问的,