XmlIgnoreAttribute, only used during serialization, not during deserialization?

前端 未结 1 1122
北荒
北荒 2021-01-18 13:25

Am I right in understanding the .NET XmlIgnoreAttribute, which says:

Instructs the Serialize method of the XmlSerializer not to serialize the public f

相关标签:
1条回答
  • 2021-01-18 14:03

    If you tag a property with XmlIgnore, it is ignored. It is not considered when the XmlSerializer builds its serialisation assembly. Therefore, XmlIgnore-d properties are not populated during deserialisation, and will be left with their default value.

    Sample program (for Snippet Compiler):

    public static void RunSnippet()
    {
      XmlSerializer ser = new XmlSerializer(typeof(Fie));
      Fie f = (Fie)(ser.Deserialize(new StringReader("<Fie><Bob>Hello</Bob></Fie>")));
      WL(f.Bob == null ? "null" : "something");
    }
    
    public class Fie
    {
      [XmlIgnore]
      public string Bob { get; set; }
    }
    

    The output from this program is null (and if you remove XmlIgnore from Fie.Bob the output is something).

    Edit in response to your edit: This is not just an implementation detail; it is indeed the documented behaviour of the attribute. From the Remarks section of the docs (first paragraph): "If you apply the XmlIgnoreAttribute to any member of a class, the XmlSerializer ignores the member when serializing or deserializing an instance of the class." (emphasis added)

    0 讨论(0)
提交回复
热议问题