C# Xml why doesn't my attribute appears?
Asked Answered
F

2

7

I have a class defined like this:

[XmlRoot(ElementName="request")]
public class Request
{
    #region Attributes
    [XmlAttribute(AttributeName = "version")]
    public string Version
    {
        get
        {
            return "1.0";
        }
    }

    [XmlAttribute(AttributeName = "action")]
    public EAction Action
    {
        get;
        set;
    }
    #endregion

But when I serialize it, "version" doesn't show up in the attribute (while "action" does).

What's going wrong?

Folberth answered 14/6, 2013 at 8:43 Comment(0)
B
4

XmlSerializer is going to ignore Version because it doesn't have a set, so there is no way it can attempt to ever deserialize it. Perhaps instead:

[XmlAttribute(AttributeName = "version")]
public string Version {get;set;}

public Request() { Version = "1.0"; }

which will have the same effect overall (although will require an extra string field per-instance - although all of the "1.0" values will be the same actual string instance, via interning), but will allow you to capture properly the version of data you are deserializing.

If you don't care about deserialization, then maybe just add a no-op set:

[XmlAttribute(AttributeName = "version")]
public string Version
{
    get { return "1.0"; }
    set { }
}
Bixler answered 14/6, 2013 at 8:48 Comment(0)
K
2

You have to set an empty setter. It's a limitation of XmlAttribute.

[XmlRoot(ElementName="request")]
public class Request
{
    #region Attributes
    [XmlAttribute(AttributeName = "version")]
    public string Version
    {
        get
        {
            return "1.0";
        }
        set{}
    }

    [XmlAttribute(AttributeName = "action")]
    public EAction Action
    {
        get;
        set;
    }
    #endregion
Kweisui answered 14/6, 2013 at 8:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.