簡體   English   中英

XmlSerializer為什么不能識別此屬性?

[英]Why does not XmlSerializer recognize this attribute?

我有一個具有兩個屬性的簡單類:

[XmlRoot("response")]
public class Response
{
    [XmlAttribute("code")]
    string Code { get; set; }

    [XmlAttribute("message")]
    string Message { get; set; }
}

我嘗試使用XmlSerializer反序列化XML字符串:

static void Main(string[] args)
{
    string xml = "<response code=\"a\" message=\"b\" />";
    using(var ms = new MemoryStream())
    using(var sw = new StreamWriter(ms))
    {
        sw.Write(xml);
        sw.Flush();

        ms.Position = 0;

        XmlSerializer ser = new XmlSerializer(typeof(Response));

        ser.UnknownAttribute += new XmlAttributeEventHandler(ser_UnknownAttribute);

        var obj = ser.Deserialize(ms);
    }
}

static void ser_UnknownAttribute(object sender, XmlAttributeEventArgs e)
{
    throw new NotImplementedException();
}

UnknownAttribute事件在code屬性處觸發,不會反序列化。
這是什么原因呢? 我使用XmlAttributeAttribute錯誤嗎?

這是因為屬性在您的課程中不是public的:

[XmlRoot("response")]
public class Response
{
    [XmlAttribute("code")]
    public string Code { get; set; }

    [XmlAttribute("message")]
    public string Message { get; set; }
}

XmlAttributeAttribute文檔中(重點是我的):

您只能將XmlAttributeAttribute分配給返回可以映射到XML架構定義語言(XSD)簡單類型之一(包括從XSD派生的所有內置數據類型)的值(或值數組)的公共字段或公共屬性。 anySimpleType類型)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM