Dimitar Tsonev
Dimitar Tsonev

Reputation: 3882

A few XmlElement attributes on a property C#

Can I have more than one XmlElement on property of a class? For example:

[XmlElement("name")]
[XmlElement("clientName")]
public string Name { .. }

I need this for deserialization. Let's say that the Name element in the XML file will be named "name" or "clientName". I want to achieve some kind of flexibility (to list the possible names for the xml element which correspond to the Name attribute.

The main idea is that I have to import XML files from another program and I have to make some kind of "templates for import".

Upvotes: 1

Views: 2536

Answers (2)

MiMo
MiMo

Reputation: 11953

Guessing that you need to import XML with two different element names for the same value you could do this:

  string _Name;

  [XmlElement("name")]
  public string Name {
    get {
      return _Name;
    }
    set {
      _Name = value;
    }
  }

  [XmlElement("clientName")]
  public string ClientName {
    get {
      return _Name;
    }
    set {
      _Name = value;
    }
  }

Upvotes: 4

Scott M.
Scott M.

Reputation: 7347

The answer is actually yes, but only under certain conditions. If you want a different element name for different types, you can do that. As for no type specified, the documentation says nothing.

[XmlElement(typeof(int),
 ElementName = "ObjectNumber"),
XmlElement(typeof(string),
 ElementName = "ObjectString")]
public ArrayList ExtraInfo;

Upvotes: 4

Related Questions