XmlSerializer System.InvalidOperationException

2023-12-20

我的应用程序中有以下代码:

[Serializable]
public class Class
{
    private string name = "";
    private List<Property> property = new List<Property>();
    [XmlAttribute]
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    [XmlArray(ElementName = "Properties")]
    public List<Property> Property
    {
        get { return property; }
        set { property = value; }
    }
    public Class() { }
}
[Serializable]
public class Property
{
    private string name = "";
    private object value;

    [XmlAttribute]
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    [XmlElement]
    public object Value
    {
        get { return this.value; }
        set { this.value = value; }
    }
    public Property() { }
}
class Program
{
    static void Main(string[] args)
    {
        List<Class> classList = GetClassList();
        SerializeConfig("test.xml", classList);
    }
    private static List<Class> GetClassList()
    {
        return new List<Class>(){
            new Class()
            {
                Name = "MyFirstClass",
                Property = new List<Property>() {
                    new Property(){ Name = "StringProperty",    Value = "Simple1"},
                    new Property(){ Name = "IntProperty",       Value = 3},
                    new Property(){ Name = "DoubleProperty",    Value = 5.5},
                    new Property(){ Name = "ListProperty",      Value = new List<int>(){
                        1,2,3,4,5
                        }
                    },
                }
            }
        };
    }
    public static List<Class> DeserializeConfig(string configPath)
    {
        if (!File.Exists(configPath)) return null;
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Class>), new XmlRootAttribute("Classes"));
            using (FileStream fs = File.Open(configPath, FileMode.Open))
            {
                return (List<Class>)serializer.Deserialize(fs);
            }
        }
        catch (Exception)
        {
            return null;
        }
    }
    public static bool SerializeConfig(string path, List<Class> config)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Class>), new XmlRootAttribute("Classes"));
            using (FileStream fs = File.Open(path, FileMode.Create))
            {
                serializer.Serialize(fs, config);
            }
        }
        catch (Exception)
        {
            return false;
        }
        return true;
    }
}

如果你运行这段代码,你会得到一个System.InvalidOperationException并显示以下消息:

{System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] may not be used in this context.
   at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write2_Property(String n, String ns, Property o, Boolean isNullable, Boolean needType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write3_Class(String n, String ns, Class o, Boolean isNullable, Boolean needType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write4_Classes(Object o)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
   at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o, XmlSerializerNamespaces namespaces)
   at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o)
   at SerializeTest.Program.SerializeConfig(String path, List`1 config) in [...]\Program.cs:line 102}

为什么我不能以这种方式序列化列表?我如何构建解决方法?


好吧,我找到了解决方案。我必须添加自定义类型。

XmlSerializer serializer = new XmlSerializer(typeof(List<Class>), null, new Type[] { typeof(List<int>) }, new XmlRootAttribute("Classes"),"");

所以我必须从我的列表中收集所有类型:

private static Type[] CollectTypesFromCollection(List<Class> collection)
{
    List<Type> types = new List<Type>();
    foreach (Class item in collection)
        foreach (Property property in item.Property)
            if (!types.Contains(property.Value.GetType()))
                types.Add(property.Value.GetType());
    return types.ToArray();
}

并且可以像这样使用序列化器:

XmlSerializer serializer = new XmlSerializer(typeof(List<Class>),null,CollectTypesFromCollection(config), new XmlRootAttribute("Classes"),"");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

XmlSerializer System.InvalidOperationException 的相关文章

随机推荐

  • Vector 与 Collections.synchronizedList(ArrayList)

    Vector 是同步的 ArrayList 是不同步的 但我们可以通过以下方式同步 ArrayListCollections synchronizedList aList 那么哪个会执行得更好更快呢 同步收集既浪费时间又危险 它们不好的一个
  • 如何在 swift 3 中通过侧菜单导航到不同的故事板

    我正在使用名为的侧菜单的第三方控件 MMD抽屉控制器 并且我使用多个故事板处理 UI 让我来看看我的侧菜单如下所示 侧菜单图像 https i stack imgur com DKVCA png 试图实现 1 当我点击父级时 应该显示 ma
  • 将 GetLastError() 转换为异常

    我有一个 Visual Studio 2008 C 项目 它使用Win32Exception类在有的情况下异常的错误 这Win32Exception类看起来像这样 defines an exception based on Win32 er
  • 如果 String s 中没有字符是 Python 中的元音,则返回 True

    我尝试寻找答案 但似乎没有任何帮助 我已经搞定了 def noVowel s return True if string s contains no vowel False otherwise for char in s if char l
  • IntelliJ 中不存在资源 nexus-maven-repository-index.properties

    在 IntelliJ 下试验 Grails 3 时 我发现了以下警告 Unindexed remote maven repositories found Disable The following repositories used in
  • Qt 自 Xcode 8 起不再工作

    自从安装 Xcode 8 以来 我在创建 Qt 控制台项目时收到此错误 项目错误 Xcode 未正确设置 您可能需要通过运行 usr bin xcodebuild 来确认许可协议 我已经重新安装了 Qt 和 Qt Creator 我读过很多
  • 程序不等待用户使用 scanf("%c",&yn) 输入;

    这是我正在编写的程序的基本代码 用于练习使用 C 中的文件 我试图检测输出文件是否已经存在 如果确实存在 我想询问用户是否愿意覆盖它 这就是我首先使用 fopen outfilename r 打开 outfilename 文件的原因 与 f
  • 如何用更少的行编写这段 JavaScript 代码来查找一棵树是否是二叉搜索树?

    在我的 Javascript 类测验中 我们被告知要制作一个简单的树并编写一个返回 true 或 false 的函数 无论它是否是 BST 我的成绩还不错 但是我被扣了10分 因为老师说 可以少6行就完成 这就是我所拥有的 function
  • 使用 ("" + ) 转换为字符串是不好的做法吗?

    在Java中转换为String是使用
  • 在 Ruby 中比较两个包含字谜字符串的数组

    如果我的代码已关闭 请原谅我 我仍然对 Ruby on Rails 很感兴趣 随着我了解更多 只是 Ruby 似乎存在一些细微的差异 尽管公平地说 我不确定我的代码是否能通过 Ruby on Rails 格式的测试 我离题了 我正在尝试比较
  • AngulareJS e2e 检查列表中的每个链接

    我是 AngularJS 的新手 我将主要使用 e2e 部分 使用 jasmine 经过几天的无果而终 至少可以说 我发现文档相当厌食 我想知道是否有人可以在这里帮助我 网站生成 a href 链接的 html 列表 我可以使用 angul
  • kotlin 数据类 + bean 验证 jsr 303

    我正在尝试让 Kotlin 在 spring data rest 项目上使用 jsr 303 验证 给出以下数据类声明 Entity data class User Id GeneratedValue strategy javax pers
  • 如何在Android中正确使用Parcelable类

    我有一个类 如下 我想通过意图发送到服务类 我已经实现了 Parcelable 接口 但不确定如何实际发送和检索整个对象 包括对象的当前状态 尤其 Override public void writeToParcel Parcel dest
  • JPA:TypedQuery 有时返回 null 而不是 NoResultException

    通常我使用 NoResultException 返回一个 空 对象 例如如果我没有从 TypedQuery 中得到结果 则返回一个空错误列表或 new BigInteger 0 现在事实证明 这有时行不通 突然 getSingleResul
  • 使用 JBoss 将消息发布到远程 JMS 队列

    这看起来很简单 但我找不到简单的答案 我想打开到远程 JMS 代理的连接 IP 和端口已知 打开到特定队列 名称已知 的会话并向该队列发布消息 是否有任何简单的 Java API 如果可能的话 标准 可以做到这一点 EDIT 好吧 我现在明
  • 环境变量文件的命名约定?

    我只是想知道是否有任何标准化约定 env环境变量文件 如果我有多个设置 例如development staging production 它们的标题应该是什么 我见过 env development development env sett
  • 快速第 n 个孩子问题

    我有一个快 nth child我正在努力解决的问题 我的目标是形成一个列表的 4 个项目分组中的每第 3 个和第 4 个项目 例如 div class normal Item 1 div div class normal Item 2 di
  • 并行执行 DocumentDb 存储过程

    documentDb 存储过程可以并行运行并更新同一对象吗 documentDb 会按顺序处理它们吗 考虑以下场景 我有一个应用程序 当我的用户完成任务时 我可以赠送 10000 个硬币 我有以下对象 remainingPoints 100
  • swift 3 结合使用语音识别和 AVFoundation

    我成功地能够使用 Speech 语音识别 并且可以使用 AVFoundation 在 Xcode 8 IOS 10 中播放 wav 文件 我只是不能同时使用它们 我有工作语音识别代码 可以在其中导入语音 当我将 AVFoundation 导
  • XmlSerializer System.InvalidOperationException

    我的应用程序中有以下代码 Serializable public class Class private string name private List