简体   繁体   中英

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

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 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 any other way?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM