简体   繁体   English

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

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

Lets say I've got an API response that looks like this 假设我有一个看起来像这样的API响应

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

I know how to create a class called ApiException and serialize to that: 我知道如何创建一个名为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);
    }
}

And I also know how to specify Element names for my properties 而且我也知道如何为我的属性指定元素名称

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; }
}

But what if I already have a class called ApiException ? 但是,如果我已经有一个名为ApiException的类呢? Say I want to call this one FootMouthAPIException 说我想把这个FootMouthAPIException

Is there any way to do that? 有没有办法做到这一点? Maybe an Data Annotation on the class itself? 也许是类本身的数据注释?

You can use the XmlRoot attribute, eg 您可以使用XmlRoot属性,例如

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

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

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