简体   繁体   中英

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:

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.
What is the reason for this? Am I using the XmlAttributeAttribute wrong?

This is because the attributes are not public in your class:

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

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).

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