首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C#中将XML反序列化为类obj

在C#中将XML反序列化为类obj
EN

Stack Overflow用户
提问于 2010-09-22 14:18:35
回答 6查看 9.5K关注 0票数 1

这是一个包含200多个这样的条目的XML文件中的条目之一。

代码语言:javascript
复制
<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>

我试图将它反序列化为一个类对象,但每次都失败。

到目前为止,这是我的代码:

代码语言:javascript
复制
using System;

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

命名空间DeserializeXML {公共类程序{

代码语言:javascript
复制
    // 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);
        }
    }


}

}

当我执行它时,我只在控制台上看到“用流读取”,而没有看到其他任何东西。

编辑

我刚意识到我说的只是“流中阅读”,因为它还在读。大约5秒后,我得到了这样的结果:

代码语言:javascript
复制
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

编辑

在将我的Program类公之于众之后,我现在得到了以下错误:

代码语言:javascript
复制
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)

编辑

对我的代码进行了大量更改(如上面所示)。有些项目列出了两次,两次检查,等等。我现在得到了这个错误:

代码语言:javascript
复制
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 ---
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-09-22 14:29:38

  1. 元素qwGroupTransId被提到了两次。您将它放在自己的元素中,并在GroupTransId上作为名称,因此反序列化器不知道将其值放在何处。
  2. FillTime的值无效。
  3. 您正在尝试反序列化一个TradeFill,但是实际的CarCollection是一个CarCollection
票数 2
EN

Stack Overflow用户

发布于 2010-09-22 14:23:06

试着改变这个:

代码语言:javascript
复制
class Program
    {

到这个

代码语言:javascript
复制
public class Program
    {

如果不指定访问修饰符,则使用默认的internal

票数 4
EN

Stack Overflow用户

发布于 2010-09-22 14:40:11

这是一个反序列化函数,它需要一个XML字符串。

代码语言:javascript
复制
public %object% DeserializeGSFiles(string content)
    {
        Type type = typeof(%object%);
        XmlSerializer xmlSerializer;
        byte[] byteArray = Encoding.UTF8.GetBytes(content);
        MemoryStream stream = new MemoryStream(byteArray);
        try
        {
            xmlSerializer = new XmlSerializer(type);
            %object% objectFromXml = (%object%)xmlSerializer.Deserialize(stream);
            return objectFromXml;
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }

用类对象替换%对象%。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3770160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档