AlexTheo
AlexTheo

Reputation: 4164

XmlSerializer and acceptable values

Hello I am working on an project in which I should serialize and deserialize my objects to Xml and back to objects. I use the XmlSerializer class in order to achieve this. So my problem is that I can't figure out how to prevent the serialization if the attribute value of an element is invalid. For example I have an element with name person which contain 1 attribute (name) I would like to prevent the user to put other names than (Alex, Nick,..) in this attribute I need something like xsd restriction (pattern) in this case but for my model. How can I solve this problem?

Upvotes: 1

Views: 378

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062590

If you just want conditional serialisation, you can do this with the ShouldSerialize* pattern. So if you have a property Name (for example), you can add:

public bool ShouldSerializeName() {
    /* validate; return true to serialize, false to skip */
}

The method needs to be public for XmlSerializer, although the same pattern works in other places (System.ComponentModel, for example) even if no-public.

Upvotes: 1

0xBADF00D
0xBADF00D

Reputation: 1034

I'm not sure weather it is a good idea to ignore some data in certain circumstances, but if you really wanna do this, take a look at the IXmlSerializable Interface. I think implementing this interface manually will be the only way to fulfill your requirements.

Upvotes: 0

Related Questions