views:

28

answers:

1

We have a schema that we serialize and deserialize into an object hierarchy. Some elements are optional in the schema. The xsd tool creates a cs file that inserts a property for each optional element. This property ends in "Specified", i.e. nameSpecified tells the serializer and deserializer to include the optional "name" element when processing. I'm trying to write a method that rips through the object hierarchy using reflection and if a property has a value and it has a "Specified" corresponding property, I want to set the Specified property to true.

I've tried to do this using reflection, ie.

 foreach(PropertyInfo p in MyObject
             .GetType()
             .GetNestedTypes()
             .GetType()
             .GetProperties()
            {
               if the field name ends in Specified check if
               there is a field with the same name without Specied. 
               If there is, and that field name has a value, then set 
               the field name that ends in Specified to true;
            }

Its the middle bit that I'm having trouble with. I preferably don't want to rip through the hierarchy and create a list of properties ending in Specified and then rip through it again to see if the corresponding name without the ending "Specified" exists and then check if it has a value. And the rip through it again to update all the Specified fields to true. Seems a bit of a long way around :(

Anyone have any bright ideas?

A: 

Add something like this to your class

This function will run prior to serializing the class.

[OnSerializing]
internal void SetSpecifiedTags(StreamingContext context)
{ 
    //do your things here. :)
}

Good luck

MSDN:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute.aspx

the_ajp
-1: this doesn't work with XML Serialization.
John Saunders