在C#中序列化多个嵌套的XmlArrays

时间:2014-07-29 12:07:52

标签: c# xml serialization nested xml-serialization

我正在尝试序列化一个包含带有嵌套元组的List的类,其中DateTimes数组作为键,并且兼作值。

以下是代码的基本版本:

类别:

[XmlRoot("Foo")]
public class Foo
{
    [XmlArray("Pairs")]
    [XmlArrayItem(typeof(Tuple<DateTime[], double>), ElementName = "Pair")]
    [XmlArrayItem(typeof(DateTime), ElementName = "DateRange"), XmlArrayItem(typeof(double), ElementName = "Value")]
    public List<Tuple<DateTime[], double>> pairs;
}

主:

class Program
{
    static void Main(string[] args)
    {
        Foo f = new Foo();
        f.pairs = new List<Tuple<DateTime[], double>>();

        f.pairs.Add(
            new Tuple<DateTime[], double>(
                new DateTime[2]{
                    new DateTime(2014,1,1),
                    new DateTime(2014,1,3),
                },
                1.1
            ));

        f.pairs.Add(
            new Tuple<DateTime[], double>(
                new DateTime[2]{
                    new DateTime(2014,2,1),
                    new DateTime(2014,2,3),
                },
                2.2
            ));

        System.Xml.Serialization.XmlSerializer writer =
            new System.Xml.Serialization.XmlSerializer(typeof(Foo));

        System.IO.StreamWriter file = new System.IO.StreamWriter(
            @"C:/Users/x/Desktop/test.xml");


    }
}

我收到了反映错误,我认为问题在于我没有正确使用这些属性,因为嵌套数组太多了。

有没有办法让这项工作,或者我是否需要创建单独的可序列化类并将它们嵌套在另一个中?

1 个答案:

答案 0 :(得分:1)

我得到的错误与嵌套数组无关。当您查看内部异常时,您最终会到达:

System.Tuple`2[System.DateTime[],System.Double] cannot be serialized 
because it does not have a parameterless constructor.

Why I could not serialize a tuple in C#?

所以我担心你必须改变你的设计......