0

我想反序列化包含 CDATA 集合的序列化 XML。

XML 看起来像这样:

<User Index="1">
   <Address><![CDATA[My street 1, 1234, My city]]></Address>
   <Address><![CDATA[My next street 1, 5678, My another city]]></Address>
</User>

因为我想直接将新地址添加为这样的字符串:

var user = new User();
user.Addresses.Add("My street 1, 1234, My city");
user.Addresses.Add("My next street 1, 5678, My another city");

我的用户类如下所示:

[XmlRoot("User", IsNullable = true)]
public class User
{
    [XmlIgnore]
    private XmlDocument xmlDoc;

    [XmlIgnore]
    private Collection<string> addresses;

    [XmlIgnore]
    private Collection<XmlNode> addressesNode;

    public User()
    {
        xmlDoc = new XmlDocument();
        addresses = new Collection<string>();
    }

    [XmlAttribute("Index")]
    public int Index { get; set; }

    [XmlElement("Address", IsNullable = true)]
    public Collection<XmlNode> AddressesNode
    {
        get
        {
            // This will create CDATA in address node. String values for
            // CDATA are in addresses collection.
            // This is causing problem.
            return new Collection<XmlNode>(addresses.Select(a => xmlDoc.CreateCDataSection(a)).ToArray());
        }
        set
        {
            // Set also address collection of string to the same values.
            addresses = new Collection<string>(value.Select(a => a.Value).ToArray());

            addressesNode = value;
        }
    }

    [XmlIgnore]
    public Collection<string> Addresses
    {
        get
        {
            return addresses;
        }
    }
}

序列化这个工作正常。但是在反序列化时,会抛出异常

 "Collection is read-only."
4

2 回答 2

0

我想你可能想打电话ToList而不是ToArray.

于 2012-08-30T14:47:55.493 回答
0

当您创建一个将 IList 作为参数传递的新集合时,它会将集合创建为原始列表的包装器。它不会将其复制到新列表中(请参见此处)。在您的 addressNode 设置器中,您创建一个新集合作为集合的包装器。您可以改为将其更改为新列表,因为 List 构造函数确实创建了一个新列表,而不是包装原始列表(请参见此处)。

于 2012-08-30T14:54:58.290 回答