How to convert xml attribute to custom object during deserialization in C# using XmlSerializer -
i
invalidcastexception: value not convertible object: system.string idtag
while attempting deserialize xml attribute.
here's 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 thrown convert.totype()
method (which called xmlserializer
). afaik there no way "implement" iconvertible
interface system.string
convert idtag
. know can implement proxy property i.e:
public class item { [xmlattribute] public string name {get; set;} [xmlattribute("parentid")] public string _parentid { get; set; } [xmlignore] public idtag parentid { { return new idtag(_parentid); } set { _parentid = value.id; } } }
is there other way?
you have tell xmlserializer
string needs in idtag
object. presumably, there's property of object want serialized (not whole object).
so, change this:
[xmlattribute] public idtag parentid { get; set; }
to this:
[xmlignore] public idtag parentidtag { get; set; } [xmlattribute] public string parentid { { return parentidtag.id; } set { parentidtag.id = value; } }
note difference between , posted - when deserialize this, parentidtag
proxy object should initialized.
Comments
Post a Comment