1

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

3
  • This seems wrong. Why do you want 2 Xml values related to a single property?
    – Dave S
    Mar 27, 2012 at 13:57
  • what does the compiler say? Also why would you want to do that. Try phrasing this as a problem you are trying to solve and this is the code I have tried and doesn't work. Mar 27, 2012 at 13:57
  • 1
    did you try it out to see if it works?
    – Scott M.
    Mar 27, 2012 at 13:57

2 Answers 2

4

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

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;
    }
  }
2
  • 1
    This will work if you can guarantee that your source data will contain either a name element or a clientName element, but not both. Otherwise, if both elements exist and have different values, this approach will cause trouble.
    – phoog
    Mar 27, 2012 at 14:15
  • 1
    @phoog: agreed - if the XML contains both elements you cannot control which one 'wins'. I am guessing tha the XML will contain one or the other elements but not both - but the question is not very clear on this.
    – MiMo
    Mar 27, 2012 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.