我的问题可能是由于对XML序列化的基本误解引起的,但无论如何...
我想序列化一个包含使用XMLSerializer初始化的数组的对象类。最小的例子:XML序列化初始化为数组
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,阅读数组不能在这里使用。如果用MyClass构造函数替换数组,例如使用一个简单的字符串,如myObject = "somestring";
,它就可以正常工作。不幸的是,我只是不知道我的对象是否会提前阵列。那么有没有解决这个问题的可能性,例如与属性或XML是在这种情况下去错误的方式?
您是否知道可以预先保存在'myObject'中的所有可能类型的对象? – dbc
向串行化添加数组定义会向xml添加不必要的标记。例如不需要标签:一个 bÇ 。这里没有标签项目:- a
- b
- c
。这两个xml都是vaild。 –
jdweng