如何将数组与 XmlSerializer 一起使用?

How to use array with XmlSerializer?

我正在做一些测试来使用它。

我有以下 xml:

<?xml version="1.0"?>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <ma>233</ma>
    <ma>2333</ma>
</test>

我有这个 class 来反序列化它:

[Serializable]
public class test
{
    public string ma { get; set; }
}

确实包含第一个元素。现在我想要两者所以我尝试设置一个数组

[Serializable]
public class test
{
    public string[] ma { get; set; }
}

但是设置一个数组我现在有 0 导致 ma 变量,而当它不是数组时我至少有第一个。

我找到了这个答案Using XmlSerializer with an array in the root element,但他使用了另一种逻辑...我想继续使用[Serializable]

您找到的答案提供了您需要的信息。 [Serializable] 对您没有帮助,因为 XmlSerializer 未使用它,请参阅 Why doesn't the XmlSerializer need the type to be marked [Serializable]?

您必须指出数组没有单独的 xml 元素来包装其项目,但数组项目直接出现在 <test> 元素下:

public class test
{
    [XmlElement]
    public string[] ma { get; set; }
}

PS。有时很难正确映射 - 我通常用测试数据填充 class 并 序列化 它,检查 XmlSerializer 的内容通常会清除什么进行中。