我想反序列化包含 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."