简体   繁体   English

XML数组反序列化为List属性失败

[英]XML array deserialization as a List property fails

I'm trying to serialize/deserialize a class that has a field of type ConcurrentBag. 我正在尝试序列化/反序列化具有ConcurrentBag类型的字段的类。

This was my approach: 这是我的方法:

public class XmlSerializable
{
    [XmlIgnore]
    public ConcurrentBag<string> Array = new ConcurrentBag<string>();
    [XmlElement(ElementName = "Array")]
    public List<string> ArrayXml { get { return Array.ToList(); } set { Array = new ConcurrentBag<string>(value); } }
}

When I try to serialize it, everything looks good, but when I try to deserialize it back, the array is empty. 当我尝试对其进行序列化时,一切看起来都不错,但是当我尝试对其进行反序列化时,该数组为空。

    XmlSerializable serializable = new XmlSerializable();
    serializable.Array.Add("entry1");

    XmlSerializer xmlSerializer = new XmlSerializer(typeof(XmlSerializable));
    StringWriter stringWriter = new StringWriter();
    XmlWriter xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true });
    xmlSerializer.Serialize(xmlWriter, serializable);
    string xml = stringWriter.ToString();
    Console.WriteLine(xml);

    StringReader stringReader = new StringReader(xml);
    XmlReader xmlReader = XmlReader.Create(stringReader);
    xmlSerializer = new XmlSerializer(typeof(XmlSerializable));

    XmlSerializable deserialized = (XmlSerializable)xmlSerializer.Deserialize(xmlReader);
    Console.WriteLine(deserialized.Array.Count);

Here is the snippet output: 这是代码段输出:

<?xml version="1.0" encoding="utf-16"?>
<XmlSerializable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Array>entry1</Array>
</XmlSerializable>
0

As you can see, the serialization works, but at deserialization, the array is empty. 如您所见,序列化有效,但是反序列化时,数组为空。

Looks to be working when class is defined like this: 像这样定义类时,看起来正在工作:

public class XmlSerializable
{
    [XmlIgnore]
    public ConcurrentBag<string> Array = new ConcurrentBag<string>();
    [XmlElement(ElementName = "Array")]
    public string[] ArrayXml { get { return Array.ToArray(); } set { Array = new ConcurrentBag<string>(value); } }
}

The property has to be string[] instead of List<string> . 该属性必须是string[]而不是List<string> Weird though, since it works with fields of type List<T> , but apparently not with properties of type List<T> . 但是很奇怪,因为它适用于List<T>类型的字段,但显然不适用于List<T>类型的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM