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

2k views Asked by At

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?

1

There are 1 answers

1
Dan Field On BEST ANSWER

You have to tell the XmlSerializer what string it needs to look for in your IdTag object. Presumably, there's a property of that object that you want serialized (not the whole object).

So, you could change this:

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

to this:

[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 you deserialize this, your ParentIdTag proxy object should be properly initialized.