簡體   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