无法将XML文件反序列化为类对象

时间:2010-09-22 14:50:28

标签: c# xml xml-serialization

这是我试图反序列化的XML文件的示例

<TradeFills>
 <TradeFill>
  <Broker>xxx</Broker>
  <CustomerAccount/>
  <qwFillTransID>xxxxxxxxxxxxxxxxxxx</qwFillTransID>
  <qwPrevTransID>xxx</qwPrevTransID>
  <qwGroupTransID>xxxxxxxxxxxxxxxxx</qwGroupTransID>
  <GroupTransID>xxxxxxxx</GroupTransID>
  <TransID>x</TransID>
  <Service>xxxxxxxxxxxxxxxx</Service>
  <Symbol>xx</Symbol>
  <Exchange>xxxxx</Exchange>
  <InstClass>xxxxxxxx</InstClass>
  <InstSubClass>xxxxxxx</InstSubClass>
  <ContractSymbol>xxxx</ContractSymbol>
  <ExpirationDate>xxxxxxxx</ExpirationDate>
  <Month>xx</Month>
  <Year>xxxx</Year>
  <Strike>xxx</Strike>
  <TradePCU>xxxx</TradePCU>
  <Buy>x</Buy>
  <Quantity>xx</Quantity>
  <Price>xxxxx</Price>
  <FillTime>xxxxxxxxxxxxxxx</FillTime>
  <PosUpdated>xxxxxxxxxxx</PosUpdated>
  <Description/>
 </TradeFill>
</TradeFills>

这是我正在使用的代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace DeserializeXML
{
    public class Program
    {

        // This is the class that will be deserialized.
        [Serializable()]
        public class TradeFill
        {
            [XmlElement("Broker")]
            public string broker;

            [XmlElement("qwFillTransID")]
            public string qwFillTransId;

            [XmlElement("qwPrevTransID")]
            public string qwPrevTransId;

            [XmlElement("qwGroupTransID")]
            public string qwGroupTransId;

            [XmlElement("GroupTransID")]
            public string GroupTransID;

            [XmlElement("TransID")]
            public string TransId;

            [XmlElement("Service")]
            public string Service;

            [XmlElement("Exchange")]
            public string Exchange;

            [XmlElement("InstClass")]
            public string InstClass;

            [XmlElement("InstSubClass")]
            public string InstSubClass;

            [XmlElement("ContractSymbol")]
            public string ConSymbol;

            [XmlElement("ExpirationDate")]
            public DateTime ExpDate;

            [XmlElement("Month")]
            public int month;

            [XmlElement("Year")]
            public int year;

            [XmlElement("Strike")]
            public double strike;

            [XmlElement("TradePCU")]
            public string TradePCU;

            [XmlElement("Buy")]
            public int buy;

            [XmlElement("Quantity")]
            public int quantity;

            [XmlElement("Price")]
            public double price;

            [XmlElement("FillTime")]
            public DateTime FillTime;

            [XmlElement("PosUpdated")]
            public string PosUpdated;

        }


        [XmlRootAttribute("TradeFills")]
        public class SIGTrades
        {
            [XmlElement("TradeFills")]
            public TradeFill[] TradeFills{ get; set; }
        }


        [Serializable()]
        public class Test
        {
             public static void Main()
            {
                Test t = new Test();
              // Read a purchase order.
                t.DeserializeObject("c:\\testtrades.xml");
            }

             private void DeserializeObject(string filename)
             {
                 Console.WriteLine("Reading with Stream");
                 // Create an instance of the XmlSerializer.
                 XmlSerializer serializer =
                 new XmlSerializer(typeof(TradeFill));
                 // Reading the XML document requires a FileStream.
                 Stream reader = new FileStream(filename, FileMode.Open);

                 // Declare an object variable of the type to be deserialized.
                 TradeFill i;

                 // Call the Deserialize method to restore the object's state.
                 i = (TradeFill)serializer.Deserialize(reader);

                 // Write out the properties of the object.
                 Console.Write(i.qwFillTransId);
             }



        }


    }
}

这是我在运行时得到的错误:

Unhandled Exception: System.InvalidOperationException: There is an error in XML
document (2, 2). ---> System.InvalidOperationException: <TradeFills xmlns=''> wa
s not expected.
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderTradeF
ill.Read3_TradeFill()
   --- End of inner exception stack trace ---

任何帮助将不胜感激。我是c#和XML的新手,不知道我哪里出错了。

2 个答案:

答案 0 :(得分:1)

您应该根据 TradeFills 类型 - NOT TradeFill类型进行反序列化。您的XML毕竟定义了 TradeFills 的实例!

因此,当您实例化反序列化器时,请使用

private void DeserializeObject(string filename)
{
    Console.WriteLine("Reading with Stream");
    // Create an instance of the XmlSerializer.
    XmlSerializer serializer = new XmlSerializer(typeof(TradeFills));
                                                        **********

TradeFills - 不是TradeFill

答案 1 :(得分:0)

我至少看到两个问题:

  • 您的XML文档无效,它缺少XML声明:

  • 您的XML显然包含TradeFill个对象的集合,并为XmlSerializer创建typeof(TradeFill)。您需要为typeof(TradeFill[])(或typeof(List<TradeFill>)或其他一些集合类型)创建序列化程序:

             XmlSerializer serializer = new XmlSerializer(typeof(TradeFill[]), new XmlRootAttribute("TradeFills"));
             // Reading the XML document requires a FileStream.
             Stream reader = new FileStream(filename, FileMode.Open);
    
             // Declare an object variable of the type to be deserialized.
             TradeFill[] tradeFills;
    
             // Call the Deserialize method to restore the object's state.
             tradeFills = (TradeFill[])serializer.Deserialize(reader);
    

注意使用XmlRootAttribute来指定根元素:如果未指定,则默认的根元素将是“ArrayOfFillItem”