问题
Am I right in understanding the .NET XmlIgnoreAttribute, which says:
Instructs the Serialize method of the XmlSerializer not to serialize the public field or public read/write property value.
that:
- The property will be deserialized, if present in the XML file?
- The property will not be serialized to a new XML file?
The reason I'm asking is that I have replaced a property in the file with a new one with more options. The old property was a simple boolean property, and the new one is an enum. I've changed the old property so that it converts the value of the new property into a boolean value, according to what the old property meant before I added the new one, both get and set has been implemented.
This allowed me to silently upgrade new files by reading the old property, which set the new property, and upon serialization, the new property was added.
However, I'd like to remove the old property from new xml files, so I was wondering what would happen if I tagged it with [XmlIgnore]
, would old xml file still deserialize properly and read that property from the file, or would it be ignored completely?
If not, would the following change do what I want?
[XmlAttribute("is-list")]
[DefaultValue(false)]
public bool IsList
{
get { return false; }
set {
if (value)
ListHandling = ListHandling.All;
}
}
This would return false for all new objects, which would be ignored since I have specified a default value, and if present in an old file, and set to true, that would change the ListHandling property, which is the new one that is important.
Edit: Upon testing, I have verified that both approaches seems to do what I want. I'll leave the question though, as I would still like to know if the first behaviour noted above is just an implementation detail, or if the documentation can be understood that way.
回答1:
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)
来源:https://stackoverflow.com/questions/2350453/xmlignoreattribute-only-used-during-serialization-not-during-deserialization