简体   繁体   English

XmlSerializer为什么不能识别此属性?

[英]Why does not XmlSerializer recognize this attribute?

I have a simple class with two properties: 我有一个具有两个属性的简单类:

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

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

I try to deserialize an XML string with XmlSerializer: 我尝试使用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();
}

The UnknownAttribute event gets fired at the code attribute, it does not get deserialized. UnknownAttribute事件在code属性处触发,不会反序列化。
What is the reason for this? 这是什么原因呢? Am I using the XmlAttributeAttribute wrong? 我使用XmlAttributeAttribute错误吗?

This is because the attributes are not public in your class: 这是因为属性在您的课程中不是public的:

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

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

From the documentation of XmlAttributeAttribute (emphasis is mine): XmlAttributeAttribute文档中(重点是我的):

You can assign the XmlAttributeAttribute only to public fields or public properties that return a value (or array of values) that can be mapped to one of the XML Schema definition language (XSD) simple types (including all built-in datatypes derived from the XSD anySimpleType type). 您只能将XmlAttributeAttribute分配给返回可以映射到XML架构定义语言(XSD)简单类型之一(包括从XSD派生的所有内置数据类型)的值(或值数组)的公共字段或公共属性。 anySimpleType类型)。

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

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