c# - 使用空数组反序列化 XML 返回一个包含单个对象的数组

标签 c# .net xml deserialization

当反序列化一个包含空数组的 XML 时,我希望这个数组为空。相反,我得到一个包含单个对象的数组,所有属性都设置为 null。

类:

[XmlRoot(ElementName = "item")]
public class Item
{
    [XmlElement(ElementName = "name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName = "thing")]
public class Thing
{
    [XmlElement(ElementName = "items")]
    public Item[] Items { get; set; }
}

XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<thing>
  <items/>
</thing>

测试:

[Fact]
public void DeserializeTest()
{
    var xml = ""; // XML here

    var serializer = new XmlSerializer(typeof(Thing));

    using (TextReader reader = new StringReader(xml))
    {
        var thing = serializer.Deserialize(reader) as Thing;

        thing.Items.Should().BeNull(); // fails
    }
}

我得到的: enter image description here

我一定是遗漏了什么?

最佳答案

您应该使用 XmlArray 属性来定义您的数组。该声明应该有效:

[XmlRoot("item")]
public class Item
{
    [XmlElement("name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName = "thing")]
public class Thing
{
    [XmlArray("items")]
    public Item[] Items { get; set; }
}

关于c# - 使用空数组反序列化 XML 返回一个包含单个对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56936968/

相关文章:

.net - 如何测试 '-'是否存在,但字符 '['和 ']'之间不存在?

c# - C# App 中显示游戏图形的最佳方向

c# - 反编译.Net代码: lambda expressions

android - 在焦点 EditText 问题处隐藏工具栏

c# - SqlBulkCopy 是否在环境事务中登记?

c# - 使用 linq 选择子列表包含的列表是另一个列表中的所有项目

c# - 5.0 之前的 c# 中的异步编程没有 async & await?

c# - 条件 Lambda 表达式?

xml - 为什么此 XSLT 转换后没有出现输出?

c++ - xalan 和 xerces 的多个版本