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,410
  • 5
  • 23
  • 36
  • http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document – Paul Michaels Jul 10 '14 at 06:59
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Jul 10 '14 at 06:59
  • @pm_2 my xml is different then the example you posted, that xml is quite easy to parse & populate. – KhanZeeshan Jul 10 '14 at 07:01
  • What is tricky? What did you try? What does your class look like? – Emond Jul 10 '14 at 07:02
  • @ErnodeWeerd thats the question, what should be the structure of the class, as XML-Tag "To" & "From" has Attribute as well as Data in its node without any child nodes. – KhanZeeshan Jul 10 '14 at 07:04

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900