Ignore a property during xml serialization but not during deserialization

后端 未结 2 1590
花落未央
花落未央 2020-12-01 03:17

In C#, how can I make XmlSerializer ignore a property during serialization but not during deserialization? (Or how do I do the same with Json.net?)

To prevent a prop

2条回答
  •  庸人自扰
    2020-12-01 04:06

    If you want to ignore the element at serialization with XmlSerializer, you can use XmlAttributeOverrides:

    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
    XmlAttributes attribs = new XmlAttributes();
    attribs.XmlIgnore = true;
    attribs.XmlElements.Add(new XmlElementAttribute("YourElementName"));
    overrides.Add(typeof(YourClass), "YourElementName", attribs);
    
    XmlSerializer ser = new XmlSerializer(typeof(YourClass), overrides);
    ser.Serialize(...
    

提交回复
热议问题