尝试将XML反序列化为C#时出现SystemInvalidOperationException

时间:2016-08-11 16:13:35

标签: c# xml

我的XML看起来像这样:

<constituencyResults>
  <constituencyResult seqNo="1">
    <consituencyId>2</consituencyId>
    <constituencyName>Aberconwy</constituencyName>
    <results>
        <result>
          <partyCode>LAB</partyCode>
          <votes>8994</votes>
          <share>33.00</share>
        </result>
        <result>
          <partyCode>CON</partyCode>
          <votes>7924</votes>
          <share>29.10</share>
        </result>
    </results>
  </constituencyResult>
</constituencyResults>

指向整个文件的链接是here

当我使用Visual Studio的Paste Special As XML Classes时,我得到以下类:

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class ConstituencyResults
    {

        private constituencyResultsConstituencyResult constituencyResultField;

        /// <remarks/>
        public constituencyResultsConstituencyResult constituencyResult
        {
            get
            {
                return this.constituencyResultField;
            }
            set
            {
                this.constituencyResultField = value;
            }
        }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class constituencyResultsConstituencyResult
    {

        private byte consituencyIdField;

        private string constituencyNameField;

        private constituencyResultsConstituencyResultResult[] resultsField;

        private byte seqNoField;

        /// <remarks/>
        public byte consituencyId
        {
            get
            {
                return this.consituencyIdField;
            }
            set
            {
                this.consituencyIdField = value;
            }
        }

        /// <remarks/>
        public string constituencyName
        {
            get
            {
                return this.constituencyNameField;
            }
            set
            {
                this.constituencyNameField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("result", IsNullable = false)]
        public constituencyResultsConstituencyResultResult[] results
        {
            get
            {
                return this.resultsField;
            }
            set
            {
                this.resultsField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public byte seqNo
        {
            get
            {
                return this.seqNoField;
            }
            set
            {
                this.seqNoField = value;
            }
        }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class constituencyResultsConstituencyResultResult
    {

        private string partyCodeField;

        private ushort votesField;

        private decimal shareField;

        /// <remarks/>
        public string partyCode
        {
            get
            {
                return this.partyCodeField;
            }
            set
            {
                this.partyCodeField = value;
            }
        }

        /// <remarks/>
        public ushort votes
        {
            get
            {
                return this.votesField;
            }
            set
            {
                this.votesField = value;
            }
        }

        /// <remarks/>
        public decimal share
        {
            get
            {
                return this.shareField;
            }
            set
            {
                this.shareField = value;
            }
        }
    }

当我尝试使用XmlSerializer这样的方式对它们进行反序列化时:(ConstituencyResults) reader.Deserialize(file);

我得到一个例外

  

SystemInvalidOperationException InnerException:{“没想到。”}

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

我稍微改变你的代码以获得你的错误但是,从我看来,它正常工作。 xml文件名为“XMLFile1.xml”,位于bin文件夹中。

<?xml version="1.0" encoding="utf-8" ?>
<ConstituencyResults>
  <ConstituencyResult SeqNo="1">
      <ConsituencyId>2</ConsituencyId>
      <ConstituencyName>Aberconwy</ConstituencyName>
      <Results>
         <Result>
            <PartyCode>LAB</PartyCode>
            <Votes>8994</Votes>
            <Share>33.00</Share>
         </Result>
         <Result>
            <PartyCode>CON</PartyCode>
            <Votes>7924</Votes>
            <Share>29.10</Share>
         </Result>
      </Results>
  </ConstituencyResult>
</ConstituencyResults>

这是“ConstituencyResults.cs”这里的所有内容。我确实更改了变量的名称,使其更具可读性。

using System;
using System.ComponentModel;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
   [SerializableAttribute()]
   [DesignerCategoryAttribute("code")]
   [XmlTypeAttribute(AnonymousType = true)]
   [XmlRootAttribute(Namespace = "", IsNullable = false)]
   public class ConstituencyResults
   {
      private ConstituencyResult _constituencyResultField;

      public ConstituencyResult ConstituencyResult
      {
         get { return _constituencyResultField; }
         set { _constituencyResultField = value; }
      }
   }

   [SerializableAttribute()]
   [DesignerCategoryAttribute("code")]
   [XmlTypeAttribute(AnonymousType = true)]
   public class ConstituencyResult
   {
      private byte _consituencyIdField;
      private string _constituencyNameField;
      private ConstituencyData[] Data;
      private byte _seqNoField;

      public byte ConsituencyId
      {
         get { return _consituencyIdField; }
         set { _consituencyIdField = value; }
      }

      public string ConstituencyName
      {
         get { return _constituencyNameField; }
         set { _constituencyNameField = value; }
      }

      [XmlArrayItemAttribute("Result", IsNullable = false)]
      public ConstituencyData[] Results
      {
        get { return Data; }
        set { Data = value; }
      }

      [XmlAttributeAttribute()]
      public byte SeqNo
      {
        get { return _seqNoField; }
        set { _seqNoField = value; }
      }
   }

   [SerializableAttribute()]
   [DesignerCategoryAttribute("code")]
   [XmlTypeAttribute(AnonymousType = true)]
   public class ConstituencyData
   {
      private string _partyCodeField;
      private ushort _votesField;
      private decimal _shareField;

      public string PartyCode
      {
         get { return _partyCodeField; }
         set { _partyCodeField = value; }
      }

      public ushort Votes
      {
         get { return _votesField; }
         set { _votesField = value; }
      }

      public decimal Share
      {
         get { return _shareField; }
         set { _shareField = value; }
      }
   }
}

程序“Program.cs”,其中我打印对象的值。

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
   public class Program
   {
      static void Main(string[] args)
      {
         XmlSerializer oSerializer = new XmlSerializer(typeof(ConstituencyResults));
         FileStream oFileStream = new FileStream("XMLFile1.xml", FileMode.Open);
         ConstituencyResults obj = (ConstituencyResults)oSerializer.Deserialize(oFileStream);
         int iCnt = 0;

         Console.WriteLine("Name : " + obj.ConstituencyResult.ConstituencyName);
         Console.WriteLine("ID : " + obj.ConstituencyResult.ConsituencyId);

         foreach (var v in obj.ConstituencyResult.Results)
         {
            iCnt++;
            Console.WriteLine("");
            Console.WriteLine("Record #" + iCnt.ToString());
            Console.WriteLine("   PartyCode : " + v.PartyCode);
            Console.WriteLine("   Share : " + v.Share);
            Console.WriteLine("   Votes : " + v.Votes);
         }

         Console.ReadKey();
      }
   }
}

结果: Console result

在这种情况下,我使用FileStream作为'file'参数。

答案 1 :(得分:1)

您遇到此问题是因为您在生成后重命名了类。

如果您使用&#34;将XML粘贴为类&#34; 功能,则所有生成的类的名称应与XML文件中的字母大小写相同。

因为您在生成constituencyResults之后将ConstituencyResults课程重命名为您在问题中遇到的错误。请注意c字母的差异。

您有两种解决方案:

  • 通过将ConstituencyResults重命名为更改constituencyResults之前的格式来撤消您的更改。
  • 通过使用XmlElement进行装饰,为所有已修改的类,属性等添加XmlElement属性,例如XmlElement("constituencyResults") ConstituencyResults