I'm using Xml to store settings for an application, which are changed during runtime and serialized and deserialized multiple times during application execution.
There is an Xml element which could hold any serializable type, and should be serialized from and deserialized to a property of type Object
, i.e.
[Serializable]
public class SetpointPoint
{
[XmlAttribute]
public string InstrumentName { get; set; }
[XmlAttribute]
public string Property { get; set; }
[XmlElement]
public object Value { get; set; }
} // (not comprehensive, only important properties displayed)
Xml,
<?xml version="1.0" encoding="utf-8"?>
<StationSetpoints xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://www.w3schools.com StationSetpoints.xsd">
<Setpoint PartNumber="107983">
<Point InstrumentName="PD Stage" Property="SetPoint">
<Value xsi:type="xsd:string">3</Value>
</Point>
<Point InstrumentName="TR Camera" Property="MeasurementRectangle" StationSetpointMemberType="Property">
<Value xsi:type="xsd:string">{X=145,Y=114,Width=160,Height=75}</Value>
</Point>
</Setpoint>
</StationSetpoints>
I deserialize the Xml and parse the properties to find an instrument object by "InstrumentName", and that instrument will have a property named the same as the Xml attribute "Property", and my intent is to set that instrument.property = the Value element in the xml. It's trivial to convert an object using Reflection such as (in vb.net)
Dim ii = InstrumentLoader.Factory.GetNamed(point.InstrumentName)
Dim pi = ii.GetType().GetProperty(point.Property)
Dim tt = pi.PropertyType
Dim vt = Convert.ChangeType(point.Value, tt)
pi.SetValue(ii, vt)
right, that works if point.Value is an object, however it is not. What gets serialized from the object turns out to be a string. In the case of when the property is a Double, we get
<Value xsi:type="xsd:string">3</Value>
yields "3"
, and when a System.Drawing.Rectangle,
<Value xsi:type="xsd:string">{X=145,Y=114,Width=160,Height=75}</Value>
yields "{X=145,Y=114,Width=160,Height=75}"
So is there a way to convert the Xml representation of the value type or object, directly into the .NET equivalent?
(Or must I use the Reflection / System.Activator to instantiate the object manually and convert (in the case of primitives) or string parse the properties and values (in the case of non-primitives)?)