How to convert an xml attribute to a custom object during deserialization in C # using XmlSerializer

I get

InvalidCastException: value is not a convertible object: System.String to IdTag

while trying to deserialize the xml attribute.

Here is the xml sample:

<?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> 

Class examples:

 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 the Convert.ToType() method (which is called from the XmlSerializer ). AFAIK there is no way to "implement" an IConvertible interface for System.String to convert to IdTag . I know that I can implement the proxy property ie:

 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 another way?

+7
c # xml deserialization attributes xmlserializer
source share
1 answer

You must tell the XmlSerializer which string to look for in your IdTag object. Presumably, there is a property of this object that you want to serialize (not the entire object).

So you can change this:

 [XmlAttribute] public IdTag ParentId { get; set; } 

:

 [XmlIgnore] public IdTag ParentIdTag { get; set; } [XmlAttribute] public string ParentId { get { return ParentIdTag.id; } set { ParentIdTag.id = value; } } 

Note the difference between this and what you posted - when deserializing this, your ParentIdTag proxy object must be properly initialized.

+2
source share

All Articles