C# - Xml Element with attribute and node value

dotNetkow picture dotNetkow · Jul 14, 2011 · Viewed 7.9k times · Source

I have some Xml that I need to deserialize into an object. The Xml is:

<Person>
  <Type id="1234">Bob</Type>
</Person>

and the classes are:

public class Person { public Type Type; }
public class Type {
   [XmlAttribute("id")]
   public string id;
   // another property for value "Bob" here, such as:
   public string value;  // ????
}

I'd like to deserialize this Xml using XmlSerializer.Deserialize, into the concrete objects above (avoiding using XPath, etc.)

What Xml attribute can I decorate the "Type" class with so that I have not only an "id" attribute but also a value ("Bob")?

Answer

Lourens picture Lourens · Jul 14, 2011

You would have to add a property like

[XmlText]
public string Text;