将XML序列化为具有不同名称的类

时间:2013-11-01 12:54:29

标签: c# xml xml-serialization

假设我有一个看起来像这样的API响应

<ApiException>
    <Status>400</Status>
    <Message>Foot too big for mouth</Message>
<ApiException>

我知道如何创建一个名为ApiException的类并序列化为:

public class ApiException
{
    public string Status { get; set; }
    public string Message { get; set; }
}

using (var response = ((HttpWebResponse)wex.Response))
{
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        System.Xml.Serialization.XmlSerializer serializer =
            new System.Xml.Serialization.XmlSerializer(typeof(ApiException));
        ApiException ex = (ApiException)serializer.Deserialize(reader);
    }
}

我也知道如何为我的属性指定元素名称

public class ApiException
{
    [System.Xml.Serialization.XmlElement(ElementName = "Status")]
    public string Whut { get; set; }
    [System.Xml.Serialization.XmlElement(ElementName = "Message")]
    public string Why { get; set; }
}

但是,如果我已经有一个名为ApiException的课程怎么办?假设我想称之为FootMouthAPIException

有没有办法做到这一点?也许是类本身的数据注释?

1 个答案:

答案 0 :(得分:3)

您可以使用XmlRoot属性,例如

[XmlRoot(ElementName = "ApiException")]
public class FootMouthAPIException
{
}
相关问题