简体   繁体   中英

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

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;

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;
    }
  }

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