Matt Jacobsen
Matt Jacobsen

Reputation: 5884

XmlAttributeAttribute and XmlElementAttribute

I'd like to declare both XmlAttributeAttribute and XmlElementAttribute on a property so that the xml deserializes correctly regardless of whether the property is defined as an xml element or as an xml attribute.

e.g. given

public class X
{
    [XmlElement()]
    [XmlAttribute()]        
    public string Prop
    {
        get;
        set;
    }
}

either of the following deserialize correctly:

<X>
    <Prop>XXX</Prop>
</X>

<X Prop="XXX"/>

Is this possible?

Upvotes: 2

Views: 3559

Answers (1)

Bala R
Bala R

Reputation: 108957

You can introduce a forwarding property like this

public class X
{
    [XmlElement()]
    public string Prop
    {
        get;
        set;
    }

    [XmlAttribute("Prop")]
     public string Prop1
    {
        get { return Prop; }
        set 
        {
             if (!string.IsNullOrEmpty(value))
             {
                  Prop = value;
             }
        }
    }
}

Upvotes: 4

Related Questions