繁体   English   中英

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

[英]Serialize XML to a class with a different name

假设我有一个看起来像这样的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

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

您可以使用XmlRoot属性,例如

[XmlRoot(ElementName = "ApiException")]
public class FootMouthAPIException
{
}

暂无
暂无

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

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