当反序列化一个包含空数组的 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
}
}
我一定是遗漏了什么?
最佳答案
您应该使用 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/