tags:

views:

134

answers:

1

Hello,

Does anyone know how I can use Convert.ChangeType to cast from XML to a specific class?

For example:

My Property

public Point Loc
{
    get { return GetValue<Point2D>("Loc"); }
    set { SetValue<Point2D>("Loc", value); }
}

My XML:

<Loc>
 <X>1.0</X>
 <Y>1.0</Y>   
</Loc>

Call to convert:

prop.SetValue(targetObj, 
             Convert.ChangeType(xmlProperty.Value, prop.PropertyType));

I have looked at using IConvertible but none of the methods are being called.

All of the examples I could find are using simple types. None show casting to an instance of a class.

Thank you,

Rick

A: 

Why do you think you need Convert.ChangeType()?

Surely you could just call SetValue() on the PropertyInfo object using the following overloaded SetValue method.:

prop.SetValue(targetObj,xmlProperty.Value,null);

However, you will first need to create an instance of the specific type, using something like Activator.CreateInstance() and set the individual properties for the Point. Subsequently, you then assign that point object/struct as input for the SetValue as you have it.

Wim Hollebrandse
My requirement is to be able to read from a dumbed down XML file and create any specified objects on the fly. The xml that gets created by serializing is far from simple. By using Linq-To-XML and reflection I am able to create any kind of simple object. The issue is how to create objects that require passing around complex types.
RickB
Edited my answer.
Wim Hollebrandse
Simply calling ChangeType results in an exception saying that the Value canot be converted into type Point. The documentation says that my objects needs to implement IConvertible but this does not work either. The methods that implement IConvertible never get called.
RickB