简体   繁体   中英

Serialize to XML a class containing a struct

This is the class I'm trying to serialize

[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; }
    }
    ...
}

This is how I do the serialization

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();

This is what I get

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

From what I read, this should work, but I must be missing something

The problem here comes from your readonly property. As explained in this other thread , XmlSerializer only serialize property with get/set accessibility.

What you can do is either make your property settable or change your serializer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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