将包含结构的类序列化为XML

时间:2014-08-11 13:02:09

标签: c# xml serialization struct

这是我尝试序列化的课程

[Serializable]
public class PendingAccountInfo 
{
        public AccountId AccountId { get; set; }
        public string EmailAddress { get; set; }
}

[Serializable]
public struct AccountId : IEquatable<AccountId> 
{
    private readonly int _id;

    public AccountId(int id) {
        _id = id;
    }

    public int Id {
        get { return _id; }
    }
    ...
}

这就是我如何进行序列化

XmlSerializer xmlserializer = new XmlSerializer(typeof(List<T>));
StringWriter stringWriter = new StringWriter();

XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };

XmlWriter writer = XmlWriter.Create(stringWriter, settings);

xmlserializer.Serialize(writer, value);

string result = stringWriter.ToString();

这就是我得到的

<PendingAccountInfo>
  <AccountId />
  <EmailAddress>test@test.com</EmailAddress>
</PendingAccountInfo>

从我读到的内容来看,这应该有用,但我必须遗漏一些东西

1 个答案:

答案 0 :(得分:1)

这里的问题来自您的只读属性。如此other thread中所述,XmlSerializer仅序列化具有get / set可访问性的属性。

您可以做的是使您的财产可设置或更改序列化程序。