简体   繁体   English

如何使用XmlSerializer在C#中反序列化期间将xml属性转换为自定义对象

[英]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 InvalidCastException: Value不是可转换对象:System.String到IdTag

while attempting to deserialize xml attribute. 尝试反序列化xml属性时。

Here's the sample xml: 这是示例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 ). Convert.ToType()方法(从XmlSerializer调用Convert.ToType()抛出异常。 AFAIK there is no way to "implement" IConvertible interface for System.String to convert to IdTag . AFAIK没有办法为System.String “实现” IConvertible接口转换为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. 您必须告诉XmlSerializerIdTag对象中需要查找的字符串。 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. 请注意它与您发布的内容之间的区别 - 当您反序列化时,应正确初始化ParentIdTag代理对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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