Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate Class Object From XML

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">[email protected]</To>
      <From EmailType="Work">[email protected]</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.

like image 574
KhanZeeshan Avatar asked Feb 13 '26 04:02

KhanZeeshan


1 Answers

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.

like image 79
Marc Gravell Avatar answered Feb 15 '26 07:02

Marc Gravell