I get
InvalidCastException: Value is not a convertible object: System.String to IdTag
while attempting to deserialize xml attribute.
Here's the sample xml:
<?xml version="1.0" encoding="windows-1250"?>
<ArrayOfItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Item Name="Item Name" ParentId="SampleId" />
</ArrayOfItem>
Sample classes:
public class Item
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public IdTag ParentId { get; set; }
}
[Serializable]
public class IdTag
{
public string id;
}
The exception is thrown from Convert.ToType()
method (which is called from XmlSerializer
). AFAIK there is no way to "implement" IConvertible
interface for System.String
to convert to IdTag
. I know I can implement a proxy property i.e:
public class Item
{
[XmlAttribute]
public string Name {get; set;}
[XmlAttribute("ParentId")]
public string _ParentId { get; set; }
[XmlIgnore]
public IdTag ParentId
{
get { return new IdTag(_ParentId); }
set { _ParentId = value.id; }
}
}
Is there any other way?
You have to tell the
XmlSerializer
what string it needs to look for in yourIdTag
object. Presumably, there's a property of that object that you want serialized (not the whole object).So, you could change this:
to this:
Note the difference between this and what you posted - when you deserialize this, your
ParentIdTag
proxy object should be properly initialized.