XML importer - truly optional fields?

How can I define a property to load from XML that is truly optional, eg may not appear in the XML at all?

Using the following:

[XmlElement(IsNullable = true)]

Only means I can put empty / null value, but the property must still appear in XML. I tried adding this:

[ContentSerializerAttribute(Optional = true)]

But it still crash when I try to load the XML unless the optional field appears in XML. So how can I add a truly optional field that may or may not appear in XML?


Bump :slight_smile:

Can you please specify what XML attribute you want to be optional?
AN entire class, attribute or property?

If you see this SO article, there shouldn’t be anything special to omit a property.

Naming is optional. You should be able to deserialise the XML so long as it has XML content matching your class def, it usually only fails if there is an element that is not recognised. (hence why naming is useful)

Hope this helps.

You are right, that putting “IsNullable” does make it mandatory.

Sorry for late response, was at work…

Anyway the following member for example:

class SomeClass {
        [ContentSerializerAttribute(Optional = true)]
        public int? test = null;

Will produce the following error:

An unhandled exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll
Additional information: Unable to read beyond the end of the stream.

Which is the same error I get without the ContentSerializerAttribute. The only thing that remove the error it is adding a “test” node with a value in it, but like I said, I want it to be optional, not mandatory with null.

Regarding your link: he’s using plain C# XML serializer, I’m using MonoGame XML serializer (when you load XML via the content manager). They are not the same.

Hope the question is more clear now, thanks! :slight_smile: