简体   繁体   中英

Serialize XML to a class with a different name

Lets say I've got an API response that looks like this

<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:

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 ? Say I want to call this one FootMouthAPIException

Is there any way to do that? Maybe an Data Annotation on the class itself?

You can use the XmlRoot attribute, eg

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

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