初始化为数组的对象的XML序列化 [英] XML Serialization of an object initialized as array

查看:80
本文介绍了初始化为数组的对象的XML序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题可能是由对XML序列化的基本误解引起的,但是无论如何...
我正在尝试序列化一个包含使用XMLSerializer类用数组初始化的对象的类.最小的例子:

My question is probably arising from a basic misunderstanding of XML serialization, but anyways...
I'm trying to serialize a class containing an object which was initialized with an array using XMLSerializer class. Minimal example:

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

namespace XMLSerializationTest
{
class Program
{
    static void Main(string[] args)
    {           
        try
        {                
            string xmlFileName = Environment.CurrentDirectory + @"\somename.xml";
            XmlSerializer writer = new XmlSerializer(typeof(MyClass));
            FileStream file = File.Create(xmlFileName);
            MyClass someclass = new MyClass();
            writer.Serialize(file, someclass);
            file.Close();
        }
        catch (Exception exc)
        {
            Console.WriteLine(exc);
        }
        Console.ReadLine();
    }        
}
public class MyClass
{
    public object myObject;
    public MyClass()
    {
        myObject = new string[1] { "somestring" };
    }
}
}

但是,这将引发System.InvalidOperationException,此处无法使用读取数组.如果有人用例如myObject = "somestring";这样的简单字符串替换MyClass构造函数中的数组,它会很好地工作.不幸的是,我只是不知道我的对象是不是数组.所以有可能解决这个问题,例如属性或在这种情况下XML只是错误的方法?

However, this throws System.InvalidOperationException, reading the array can't be used here. It works fine, if one replaces the array within the MyClass constructor, e.g., with a simple string like myObject = "somestring";. Unfortunately, I just don't know if my object will be an array or not in advance. So is there any possibility to solve this problem e.g. with attributes or is XML just the wrong way to go in this case?

推荐答案

您的困难来自于这样一个事实,即XmlSerializer要求通过反射将所有类型序列化为可静态发现的序列.但是,您的类型MyClass具有一个多态的object属性,在该属性中存储了object子类型(特别是string [])的子类型的实例.当XmlSerializer遇到它时,由于不需要这种类型的对象,因此序列化程序将引发您看到的异常.

Your difficulty arises from the fact that XmlSerializer requires all types to be serialized to be discoverable statically, through reflection. However, your type MyClass has a polymorphic object property where a instance of a subtype of object -- specifically string [] -- is being stored. When XmlSerializer encounters it, since objects of this type are not expected, the serializer throws the exception you see.

序列化诸如此类的多态属性时,必须使用 XML序列化属性声明可以遇到的类型. XmlSerializer提供了两种实现此目的的机制.

When serializing polymorphic properties such as this, it is necessary to use XML serialization attributes to declare the types that can be encountered. XmlSerializer provides two mechanisms to accomplish this.

  1. 使用 XmlInclude(Type) 包含类型上的属性.由于stringstring []object属性的可能类型,因此您应该执行以下操作:

  1. Declare the possible polymorphic subtypes using XmlInclude(Type) attributes on the containing type. Since string and string [] are the possible types of your object property, you would do:

[XmlInclude(typeof(string))]
[XmlInclude(typeof(string[]))]
public class MyClass
{
    public object myObject { get; set; }

    public MyClass()
    {
        myObject = new string[] { "somestring" };
    }
}

生成的XML将如下所示:

And the resulting XML will look like:

<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <myObject xsi:type="ArrayOfString">
        <string>somestring</string>
    </myObject>
</MyClass>

是否注意到 xsi:type 属性?这是 w3c标准属性,它允许元素显式声明其类型.它的存在允许XmlSerializer将XML反序列化为与最初序列化的对象相同类型的对象.

Notice the xsi:type attribute? That is a w3c standard attribute that allows the element to assert its type explicitly. Its presence allows XmlSerializer to deserialize the XML into the same type of objects as were originally serialized.

(请注意,[XmlInclude(typeof(string))]似乎是不必要的,因为string显然是内置的已知类型-尽管我找不到可以证实这一点的文档.)

(Note that [XmlInclude(typeof(string))] seems to be unnecessary as string is apparently a built-in known type - though I cannot find documentation confirming this.)

使用 [XmlElement(String, Type)] 声明可能的多态子类型.关于多态属性本身.因此,您将执行以下操作:

Declare the possible polymorphic subtypes using [XmlElement(String, Type)] on the polymorphic property itself. Thus you would do something like:

public class MyClass
{
    [XmlElement("myObjectString", typeof(string))]
    [XmlElement("myObjectStringArray", typeof(string[]))]
    public object myObject { get; set; }

    public MyClass()
    {
        myObject = new string[] { "somestring" };
    }
}

生成的XML将如下所示:

And the XML generated will look like:

<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <myObjectStringArray>
        <string>somestring</string>
    </myObjectStringArray>
</MyClass>

请注意,myObject元素的名称已修改为传递给[XmlElement(String, Type)]属性构造函数的字符串.这样,XmlSerializer可以将XML反序列化为与最初序列化的对象相同类型的对象.

Notice that the name of the myObject element been modified to the string passed to into the [XmlElement(String, Type)] attribute constructor. This allows XmlSerializer to deserialize the XML into the same type of objects as were originally serialized.

这篇关于初始化为数组的对象的XML序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆