3

I'm having some problem populating given below XML to class, I know how to populate class object from XML(Deserialization) but below XML is tricky for me.

<Header>
      <To EmailType="Personal">abc@abc.com</To>
      <From EmailType="Work">abc2@abc.com</From>
</Header>

if I create below class, it will only populate the data part of the XML not the attribute,

[XmlRoot(ElementName = "Header")]
    public class Header
    {
        public Header()
        {

        }

        [XmlElement(ElementName = "To", Form = XmlSchemaForm.Unqualified)]
        public string To { get; set; }


        [XmlElement(ElementName = "From", Form = XmlSchemaForm.Unqualified)]
        public string From { get; set; }
}

I want to be able to parse & save both attribute & data.

KhanZeeshan
  • 1,397
  • 5
  • 21
  • 34

1 Answers1

3

I'm assuming what you want is to deserialize it as something like:

public string ToAddress {get;set;}
public EmailType ToEmailType {get;set;} // an enum
public string FromAddress {get;set;}
public EmailType FromEmailType {get;set;}

unfortunately, that is not possible with XmlSerializer. You would have to have a hierarchical model:

public EmailDetails To {get;set;}
public EmailDetails From {get;set;}

...

public class EmailDetails {
    [XmlAttribute]
    public EmailType EmailType {get;set;}
    [XmlText]
    public string Address {get;set;}
}

Alternatively, you will have to parse it manually via XElement or similar.

Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830