c# – .NET XML序列化错误(反映类型有错误)

是的,我知道非常通用的标题,但我现在要解释.

鉴于下面的类定义,有人可以解释为什么我在调用Serialize()方法时会遇到此异常.

{“有一个错误反映了’FNM.MISMO_3_0.FOREIGN_OBJECT’类型.”}

{“选择标识符’ItemsElementName’的类型与’Items’的类型不一致.请使用System.Collections.Generic.List`1 [[MISMO_3_0.ItemsChoiceType,MISMO_3_0,Version = 1.0.0.0,Culture = neutral,PublicKeyToken]的数组= NULL]].“}

谢谢,
斯蒂芬

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml","4.0.30319.225")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.mismo.org/residential/2009/schemas")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.mismo.org/residential/2009/schemas",IsNullable = true)]
public partial class FOREIGN_OBJECT
{

    private List<object> itemsField;

    private List<ItemsChoiceType> itemsElementNameField;

    private MISMOresourceLink typeField;

    private bool typeFieldSpecified;

    private string roleField;

    private string titleField;

    private string labelField;

    private string sequenceNumberField;

    private static System.Xml.Serialization.XmlSerializer serializer;

    public FOREIGN_OBJECT()
    {
        this.itemsElementNameField = new List<ItemsChoiceType>();
        this.itemsField = new List<object>();
    }

    [System.Xml.Serialization.XmlElementAttribute("CharacterEncodingSetType",typeof(CharacterEncodingSetEnum),Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("CharacterEncodingSetTypeOtherDescription",typeof(MISMOString),Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("EXTENSION",typeof(EXTENSION),Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("EmbeddedContentXML",typeof(MISMOXML),Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("MIMETypeIdentifier",typeof(MISMOIdentifier),Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("ObjectCreatedDatetime",typeof(MISMODatetime),Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("ObjectDescription",Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("ObjectEncodingType",typeof(ObjectEncodingEnum),Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("ObjectEncodingTypeOtherDescription",Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("ObjectName",Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("ObjectURI",typeof(string),DataType = "anyURI",Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("OriginalCreatorDigestValue",typeof(MISMOValue),Order = 0)]
    [System.Xml.Serialization.XmlElementAttribute("REFERENCE",typeof(REFERENCE),Order = 0)]
    [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
    public List<object> Items
    {
        get
        {
            return this.itemsField;
        }
        set
        {
            this.itemsField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute("ItemsElementName",Order = 1)]
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public List<ItemsChoiceType> ItemsElementName
    {
        get
        {
            return this.itemsElementNameField;
        }
        set
        {
            this.itemsElementNameField = value;
        }
    }

    [System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified,Namespace = "http://www.w3.org/1999/xlink")]
    public MISMOresourceLink type
    {
        get
        {
            return this.typeField;
        }
        set
        {
            this.typeField = value;
        }
    }

    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool typeSpecified
    {
        get
        {
            return this.typeFieldSpecified;
        }
        set
        {
            this.typeFieldSpecified = value;
        }
    }

    [System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified,Namespace = "http://www.w3.org/1999/xlink")]
    public string role
    {
        get
        {
            return this.roleField;
        }
        set
        {
            this.roleField = value;
        }
    }

    [System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified,Namespace = "http://www.w3.org/1999/xlink")]
    public string title
    {
        get
        {
            return this.titleField;
        }
        set
        {
            this.titleField = value;
        }
    }

    [System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified,Namespace = "http://www.w3.org/1999/xlink",DataType = "NMTOKEN")]
    public string label
    {
        get
        {
            return this.labelField;
        }
        set
        {
            this.labelField = value;
        }
    }

    [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")]
    public string SequenceNumber
    {
        get
        {
            return this.sequenceNumberField;
        }
        set
        {
            this.sequenceNumberField = value;
        }
    }

    private static System.Xml.Serialization.XmlSerializer Serializer
    {
        get
        {
            if ((serializer == null))
            {
                serializer = new System.Xml.Serialization.XmlSerializer(typeof(FOREIGN_OBJECT));
            }
            return serializer;
        }
    }

    #region Serialize/Deserialize
    /// <summary>
    /// Serializes current FOREIGN_OBJECT object into an XML document
    /// </summary>
    /// <returns>string XML value</returns>
    public virtual string Serialize(System.Text.Encoding encoding)
    {
        System.IO.StreamReader streamReader = null;
        System.IO.MemoryStream memoryStream = null;
        try
        {
            memoryStream = new System.IO.MemoryStream();
            System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
            xmlWriterSettings.Encoding = encoding;
            System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream,xmlWriterSettings);
            Serializer.Serialize(xmlWriter,this);
            memoryStream.Seek(0,System.IO.SeekOrigin.Begin);
            streamReader = new System.IO.StreamReader(memoryStream);
            return streamReader.ReadToEnd();
        }
        finally
        {
            if ((streamReader != null))
            {
                streamReader.Dispose();
            }
            if ((memoryStream != null))
            {
                memoryStream.Dispose();
            }
        }
    }

    public virtual string Serialize()
    {
        return Serialize(Encoding.UTF8);
    }

    /// <summary>
    /// Deserializes workflow markup into an FOREIGN_OBJECT object
    /// </summary>
    /// <param name="xml">string workflow markup to deserialize</param>
    /// <param name="obj">Output FOREIGN_OBJECT object</param>
    /// <param name="exception">output Exception value if deserialize failed</param>
    /// <returns>true if this XmlSerializer can deserialize the object; otherwise,false</returns>
    public static bool Deserialize(string xml,out FOREIGN_OBJECT obj,out System.Exception exception)
    {
        exception = null;
        obj = default(FOREIGN_OBJECT);
        try
        {
            obj = Deserialize(xml);
            return true;
        }
        catch (System.Exception ex)
        {
            exception = ex;
            return false;
        }
    }

    public static bool Deserialize(string xml,out FOREIGN_OBJECT obj)
    {
        System.Exception exception = null;
        return Deserialize(xml,out obj,out exception);
    }

    public static FOREIGN_OBJECT Deserialize(string xml)
    {
        System.IO.StringReader stringReader = null;
        try
        {
            stringReader = new System.IO.StringReader(xml);
            return ((FOREIGN_OBJECT)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
        }
        finally
        {
            if ((stringReader != null))
            {
                stringReader.Dispose();
            }
        }
    }

    /// <summary>
    /// Serializes current FOREIGN_OBJECT object into file
    /// </summary>
    /// <param name="fileName">full path of outupt xml file</param>
    /// <param name="exception">output Exception value if failed</param>
    /// <returns>true if can serialize and save into file; otherwise,false</returns>
    public virtual bool SaveToFile(string fileName,System.Text.Encoding encoding,out System.Exception exception)
    {
        exception = null;
        try
        {
            SaveToFile(fileName,encoding);
            return true;
        }
        catch (System.Exception e)
        {
            exception = e;
            return false;
        }
    }

    public virtual bool SaveToFile(string fileName,out System.Exception exception)
    {
        return SaveToFile(fileName,Encoding.UTF8,out exception);
    }

    public virtual void SaveToFile(string fileName)
    {
        SaveToFile(fileName,Encoding.UTF8);
    }

    public virtual void SaveToFile(string fileName,System.Text.Encoding encoding)
    {
        System.IO.StreamWriter streamWriter = null;
        try
        {
            string xmlString = Serialize(encoding);
            streamWriter = new System.IO.StreamWriter(fileName,false,Encoding.UTF8);
            streamWriter.WriteLine(xmlString);
            streamWriter.Close();
        }
        finally
        {
            if ((streamWriter != null))
            {
                streamWriter.Dispose();
            }
        }
    }

    /// <summary>
    /// Deserializes xml markup from file into an FOREIGN_OBJECT object
    /// </summary>
    /// <param name="fileName">string xml file to load and deserialize</param>
    /// <param name="obj">Output FOREIGN_OBJECT object</param>
    /// <param name="exception">output Exception value if deserialize failed</param>
    /// <returns>true if this XmlSerializer can deserialize the object; otherwise,false</returns>
    public static bool LoadFromFile(string fileName,out System.Exception exception)
    {
        exception = null;
        obj = default(FOREIGN_OBJECT);
        try
        {
            obj = LoadFromFile(fileName,encoding);
            return true;
        }
        catch (System.Exception ex)
        {
            exception = ex;
            return false;
        }
    }

    public static bool LoadFromFile(string fileName,out System.Exception exception)
    {
        return LoadFromFile(fileName,out exception);
    }

    public static bool LoadFromFile(string fileName,out FOREIGN_OBJECT obj)
    {
        System.Exception exception = null;
        return LoadFromFile(fileName,out exception);
    }

    public static FOREIGN_OBJECT LoadFromFile(string fileName)
    {
        return LoadFromFile(fileName,Encoding.UTF8);
    }

    public static FOREIGN_OBJECT LoadFromFile(string fileName,System.Text.Encoding encoding)
    {
        System.IO.FileStream file = null;
        System.IO.StreamReader sr = null;
        try
        {
            file = new System.IO.FileStream(fileName,FileMode.Open,FileAccess.Read);
            sr = new System.IO.StreamReader(file,encoding);
            string xmlString = sr.ReadToEnd();
            sr.Close();
            file.Close();
            return Deserialize(xmlString);
        }
        finally
        {
            if ((file != null))
            {
                file.Dispose();
            }
            if ((sr != null))
            {
                sr.Dispose();
            }
        }
    }
    #endregion

    #region Clone method
    /// <summary>
    /// Create a clone of this FOREIGN_OBJECT object
    /// </summary>
    public virtual FOREIGN_OBJECT Clone()
    {
        return ((FOREIGN_OBJECT)(this.MemberwiseClone()));
    }
    #endregion
}

解决方法

仅当ChoiceIdentifier是一个数组而不是泛型列表时,才支持XmlChoiceIdentifierAttribute中的多个元素.
[System.Xml.Serialization.XmlElementAttribute("ItemsElementName",Order = 1)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemsChoiceType[] ItemsElementName
{
    // ...
}

该错误令人困惑,因为它假设Items是类似数组(A列表)并且您的选择标识符不是数组,您在选择标识符的类型之前错过了数组限定符.但事实并非如此,所以这个建议完全是误导性的.

注意:理论上看代码(来自微软源服务器)项不需要是数组……实际上,临时序列化类的生成完全爆炸,因为List.Length不是公共的(它是显式实现的)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1:最直白的循环遍历方法,可以分为遍历key--value键值对以及所有的key两种表现形式2:用Linq的方式去查询(当然了这里要添加对应的命名空间 using System.Linq)如下为一个十分简单的代码示例:private void GetDicKeyByValue(){ Dicti...
private void ClearTextBox(){ foreach (var control in pnlDetail.Controls) { if (!(control is TextBox)) continue; var txtBox = (TextBox)control; txtBox.
原文叫看《墨攻》理解IOC概念 2006年多部贺岁大片以让人应接不暇的频率纷至沓来,其中张之亮的《墨攻》算是比较出彩的一部,讲述了战国时期墨家人革离帮助梁 国反抗赵国侵略的个人英雄主义故事,恢宏壮阔,浑雄凝重的历史场面相当震撼。其中有一个场景:当刘德华所饰的墨者革离到达梁国都城 下,城上梁国守军问:
System.Data.ConstraintException: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Request.Form value was detected from the client在使用ASP.NET MVC3 开发系统的用了百度的UEditor编辑器提交表单时遇到检测到有潜在危险的 Request.Form,我百度一下,试了网上的方法,都没用。要在Web.config增加&lt;h
右击文件夹-&gt;安全选项卡-&gt;添加-&gt;高级-&gt;立即查找Windows Server 2003:请您在目录添加IIS来宾帐号(IUSR_Hostname)的只读权限,以及Network Service组的读写修改权限。Windows Server 2000:请您在目录添加IIS来
&lt;compilationdebug=&quot;true&quot;&gt;&lt;buildProviders&gt;&lt;addextension=&quot;.html&quot;type=&quot;System.Web.Compilation.PageBuildProvider&q
在ASP.NET MVC 中 Spring.NET 配置注入的时候,下面这方式是可行的。&lt;spring&gt; &lt;context&gt; &lt;resource uri=&quot;config://spring/objects&quot; /&gt; &lt;/context&gt;
Stopwatch stopwatch = new Stopwatch();stopwatch.Start();。。。。。中间代码。。。&#x9;stopwatch.Stop();&#x9;long result = stopwatch.ElapsedMilliseconds;sqlBulkCopy.Close()
问题描述 在asp.net mvc 下配置ueditor图片上传时总是提示:缺少十六进制字符错误(IE下提示),起初还以为是我上传的图片名称中有中文字符所致,后来我又上传了英文字符名字的图片发现还是一样的错误提示:◆无赖之下只好到火狐下看错误的详情:◆第二个错误我无法解决,先看第一个,输入地址显示错
已经安装net2.0 和3.5 ,但IIS里面却只有1.1开始→运行→CMDC:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i按回车键后便会开始自动安装,安装完重启一下IIS在IIS中ASP.NET选项卡便可以看到。注
根据传进来不同的值,调用不同的方法View Code protected void btn_SwitchClick(object sender, EventArgs e){ string result = &quot;&quot;; switch (ddlMethod.SelectedValue)
整理两个 在C#中,用正则表达式 获取网页源代码标签的属性或值的方法 :1、获取标签中的值: CSDN 结果:CSDN/// /// 获取字符中指定标签的值 /// /// 字符串 /// 标签 /// 值 public static string GetTitleContent(string st
/// &lt;summary&gt;/// 集合装换DataTable/// &lt;/summary&gt;/// &lt;param name=&quot;list&quot;&gt;集合&lt;/param&gt;/// &lt;returns&gt;&lt;/returns&gt;publ
将目录下面所有的 .cs 文件合并到一个 code.cs 文件中,写著作权复制代码时的必备良药 @echo off echo 将该目录下所有.cs文件的内容合并到一个 code.cs 文件中! pause dir /ad/s/b &gt; folderPath.txt md codeTemp for
做接口开发的时候,往往接受参数或返回值是一个XML的字符串。如下图,不方便辨识 两种方法, 1.将它保存为xxx.xml,然后用浏览器打开。这种方法稍微有些麻烦。 2.使用 UltraEdit 工具
一个字段控制多个状态选项private void GenerateAdvice_OnClick(object sender, RoutedEventArgs e){ TestStatus c1 = TestStatus.A | TestStatus.C | TestStatus.E; v...
效果如下: 代码如下:
StartUp.cs public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseEndpoints(endpoints =&gt; { endpoints.MapControllerRoute(