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

本文关键字:错误 对象 xml 反序列化 | 更新日期: 2023-09-27 18:34:16

<?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);

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

我测试你的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; }
}

我想您可能会错过"货币"和"描述"字段,它们应该是可访问的,