反序列化到XML的obj类在C#序列化、XML、obj

2023-09-04 23:19:13 作者:葡萄钙奶片

这是我在超过200个这样的项目巨大的XML文件中的一个条目。

 < TradeFills>
 < TradeFill>
  <代理> XXX< /经纪人>
  < CustomerAccount />
  < qwFillTransID> xxxxxxxxxxxxxxxxxxx< / qwFillTransID>
  < QW prevTransID> XXX< / QW prevTransID>
  < qwGroupTransID> xxxxxxxxxxxxxxxxx< / qwGroupTransID>
  < GroupTransID> XXXXXXXX< / GroupTransID>
  < TRANSID&GT,X< / TRANSID>
  <服务> XXXXXXXXXXXXXXXX< /服务>
  <符号> XX< /符号>
  <交流与GT;为XXXXX< /交流与GT;
  < InstClass> XXXXXXXX< / InstClass>
  < InstSubClass> XXXXXXX< / InstSubClass>
  < ContractSymbol> XXXX< / ContractSymbol>
  < EXPIRATIONDATE> XXXXXXXX< / EXPIRATIONDATE>
  <当月> XX< /月>
  <年> XXXX< /年>
  <打击> XXX< /行使>
  < TradePCU> XXXX< / TradePCU>
  <买入&GT,X< /购买>
  <数量> XX< /数量>
  <价格>&XXXXX LT; /价格>
  < FillTime> XXXXXXXXXXXXXXX< / FillTime>
  < PosUpdated> XXXXXXXXXXX< / PosUpdated>
  <描述/>
 < / TradeFill>
< / TradeFills>
 

我在尝试反序列化到这一个类的对象,但每次都失败了。

对象序列化xml格式

这是我的code到目前为止:

 使用系统;
 

使用System.Collections.Generic; 使用System.Text; 使用System.IO; 使用的System.Xml.Serialization;

命名空间DeserializeXML {     公共类节目     {

  //这是将反序列化的类。
    [序列化()]
    公共类TradeFill
    {
        [的XmlElement(代理)]
        公共字符串经纪人;

        [的XmlElement(qwFillTransID)]
        公共字符串qwFillTransId;

        [的XmlElement(QW prevTransID)
        公共字符串QW prevTransId;

        [的XmlElement(qwGroupTransID)]
        公共字符串qwGroupTransId;

        [的XmlElement(GroupTransID)]
        公共字符串GroupTransID;

        [的XmlElement(TRANSID)
        公共字符串TRANSID;

        [的XmlElement(服务)]
        公共字符串服务;

        [的XmlElement(「联交所」)]
        公共字符串交换;

        [的XmlElement(InstClass)]
        公共字符串InstClass;

        [的XmlElement(InstSubClass)]
        公共字符串InstSubClass;

        [的XmlElement(ContractSymbol)]
        公共字符串ConSymbol;

        [的XmlElement(EXPIRATIONDATE)]
        公众的DateTime EXPDATE;

        [的XmlElement(月)
        公众诠释一个月;

        [的XmlElement(年)
        公众诠释一年;

        [的XmlElement(罢工)
        公共连击;

        [的XmlElement(TradePCU)]
        公共字符串TradePCU;

        [的XmlElement(买入)
        公众诠释购买;

        [的XmlElement(数量)
        公众诠释数量;

        [的XmlElement(价格)
        大众双价格;

        [的XmlElement(FillTime)]
        公众的DateTime FillTime;

        [的XmlElement(PosUpdated)]
        公共字符串PosUpdated;

    }


    [XmlRootAttribute(TradeFills)]
    公共类SIGTrades
    {
        [的XmlElement(TradeFills)]
        公共TradeFill [] TradeFills {获得;组; }
    }


    [序列化()]
    公共类测试
    {
         公共静态无效的主要()
        {
            测试T =新的测试();
          //读取采购订单。
            t.DeserializeObject(C:\\的test.xml);
        }

        私人无效DeserializeObject(字符串文件名)
        {
            Console.WriteLine(读与流​​);
            //创建XmlSerializer的实例。
            XmlSerializer的序列化=
            新的XmlSerializer(typeof运算(TradeFill));
            //读取XML文档都需要一个FileStream。
            流阅读器=新的FileStream(文件名,FileMode.Open);

            //声明要反序列化的类型的对象变量。
            TradeFill我;

            //调用Deserialize方法来恢复对象的状态。
            I =(TradeFill)serializer.Deserialize(读卡器);

            //写出来的对象的属性。
            Console.Write(i.qwFillTransId);
        }
    }


}
 

}

当我执行它,我只看到控制台上的阅读与流,而不是其他。

修改

我才意识到我说的只有阅读与流,因为它是还在读约5秒钟后,这是我得到了什么:

 未处理的异常:System.InvalidOperationException:DeserializeXML.Program是
 人迹罕至,由于其保护级别。只有公共类型都可以加工。
   在System.Xml.Serialization.TypeDesc.CheckSupported()
   在System.Xml.Serialization.TypeScope.GetTypeDesc(类型类型,的MemberInfo源码
E,布尔directReference,布尔throwOnError)
   在System.Xml.Serialization.TypeScope.ImportTypeDesc(类型类型,我的MemberInfo
mberInfo,布尔directReference)
   在System.Xml.Serialization.TypeScope.GetTypeDesc(类型类型,的MemberInfo源码
E,布尔directReference,布尔throwOnError)
   在System.Xml.Serialization.ModelScope.GetTypeModel(类型类型,布尔直接
参考)
   在System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(型号类型
,XmlRootAttribute根,字符串defaultNamespace)
   在System.Xml.Serialization.XmlSerializer..ctor(类型类型,字符串defaultName中
空间)
   在System.Xml.Serialization.XmlSerializer..ctor(类型类型)
   在DeserializeXML.Program.Test.DeserializeObject(字符串文件名)在C:\解决的文
经济需求测试和设置\ sobti \我的文档\ Visual Studio 2010的\项目\ DeserializeXML \
DeserializeXML \的Program.cs:行109
   在DeserializeXML.Program.Test.Main()在C:\ Documents和Settings \ sobti \我的D
议付适用银行\ Visual Studio 2010的\项目\ DeserializeXML \ DeserializeXML \的Program.cs:李
NE 102
 

修改

让我Program类公众意见后,现在我得到这个错误:

 未处理的异常:System.InvalidOperationException:有一个错误反光贴
鼎型DeserializeXML.Program.TradeFill。 ---> System.InvalidOperationExcept
离子:有一个错误反映现场GroupTransId。 ---> System.InvalidOper
ationException:XML元素的命名空间qwGroupTransId''已经是PR
ESENT在目前的范围。使用XML属性来指定其他XML名称或Na
mespace为元素。
   在System.Xml.Serialization.XmlReflectionImporter.AddUniqueAccessor(INameScop
Ë范围,存取访问)
   在System.Xml.Serialization.XmlReflectionImporter.AddUniqueAccessor(MemberMap
平成员,INameScope元素,INameScope属性,布尔isSequence)
   在System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(海峡
uctMapping映射,StructModel模型,布尔openModel,字符串的typeName,重现
sionLimiter限制器)
 

修改

做了一堆的变化,以我的code(反映以上)。曾列举了一些项目两次,双重检查情况等。现在我得到这个错误:

 未处理的异常:System.InvalidOperationException:有一个错误的XML
文件(2,2)。 ---> System.InvalidOperationException:其中,TradeFills的xmlns =''> WA
不是的预期。
   在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderTradeF
ill.Read3_TradeFill()
   ---内部异常堆栈跟踪的结尾---
 

解决方案 元素 qwGroupTransId 被提及两次。你拥有了它在自己的元素,作为GroupTransId一个名字,所以解串器不知道在哪里把它的值。 您的价值,为 FillTime 是无效的。 您正在尝试反序列化 TradeFill ,但实际的XML是 CarCollection

This is one of the entries I have in a huge XML file of over 200 such entries.

<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>

I am attempting to deserialize this into a class object but failing every time.

This is my code so far:

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:\\test.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);
        }
    }


}

}

When I execute it, I only see "Reading with Stream" on the console, and nothing else.

EDIT

I just realized I say only 'Reading with stream" because it was still reading. After about 5 seconds, this is what I got:

Unhandled Exception: System.InvalidOperationException: DeserializeXML.Program is
 inaccessible due to its protection level. Only public types can be processed.
   at System.Xml.Serialization.TypeDesc.CheckSupported()
   at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo sourc
e, Boolean directReference, Boolean throwOnError)
   at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo me
mberInfo, Boolean directReference)
   at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo sourc
e, Boolean directReference, Boolean throwOnError)
   at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean direct
Reference)
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type
, XmlRootAttribute root, String defaultNamespace)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultName
space)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type)
   at DeserializeXML.Program.Test.DeserializeObject(String filename) in c:\docum
ents and settings\sobti\my documents\visual studio 2010\Projects\DeserializeXML\
DeserializeXML\Program.cs:line 109
   at DeserializeXML.Program.Test.Main() in c:\documents and settings\sobti\my d
ocuments\visual studio 2010\Projects\DeserializeXML\DeserializeXML\Program.cs:li
ne 102

EDIT

After making my Program class public, I now get this error:

Unhandled Exception: System.InvalidOperationException: There was an error reflec
ting type 'DeserializeXML.Program.TradeFill'. ---> System.InvalidOperationExcept
ion: There was an error reflecting field 'GroupTransId'. ---> System.InvalidOper
ationException: The XML element 'qwGroupTransId' from namespace '' is already pr
esent in the current scope. Use XML attributes to specify another XML name or na
mespace for the element.
   at System.Xml.Serialization.XmlReflectionImporter.AddUniqueAccessor(INameScop
e scope, Accessor accessor)
   at System.Xml.Serialization.XmlReflectionImporter.AddUniqueAccessor(MemberMap
ping member, INameScope elements, INameScope attributes, Boolean isSequence)
   at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(Str
uctMapping mapping, StructModel model, Boolean openModel, String typeName, Recur
sionLimiter limiter)

EDIT

made a bunch of changes to my code (as reflected above). Had some items listed twice, double checked case etc. I now get this error:

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 ---

解决方案

Element qwGroupTransId is mentioned twice. You have it in its own element and as a name on GroupTransId, so the deserializer doesn't know where to put values for it. Your value for the FillTime is invalid. You're trying to deserialize a TradeFill, but the actual xml is a CarCollection.