Set XML tag name for Serialization

image_pdfimage_print
   
 
using System;
using System.IO;
using System.Xml.Serialization;

public class Serializer {

  public static void Main(string [] args) {
    Personnel personnel = CreatePersonnel();
    XmlSerializer serializer = new XmlSerializer(typeof(Personnel));
    using (FileStream stream = File.OpenWrite("Employees.xml")) {
      serializer.Serialize(stream, personnel);
    }
  }
  
  private static Personnel CreatePersonnel() {
    Personnel personnel = new Personnel();
    personnel.Employees = new Employee [] {new Employee()};
    personnel.Employees[0].FirstName = "Joe";
    personnel.Employees[0].MiddleInitial = "M";
    personnel.Employees[0].LastName = "Lee";
    
    personnel.Employees[0].Addresses = new Address [] {new Address()};
    personnel.Employees[0].Addresses[0].AddressType = AddressType.Home;
    personnel.Employees[0].Addresses[0].Street = new string [] {"999 Colluden"};
    personnel.Employees[0].Addresses[0].City = "Vancouver";
    personnel.Employees[0].Addresses[0].State = State.BC;
    personnel.Employees[0].Addresses[0].Zip = "V5V 4X7";
    
    personnel.Employees[0].HireDate = new DateTime(2001,1,1);
    
    return personnel;
  }
}


[Serializable]
public enum AddressType {
  Home,
  Office
}

[Serializable]
public enum State {
  [XmlEnum(Name="British C")]BC,
  [XmlEnum(Name="Sask")]SK
}

[Serializable]
public class Address {
  [XmlAttribute(AttributeName="type")]  public AddressType AddressType;
  [XmlElement(ElementName="street")]    public string[] Street;
  [XmlElement(ElementName="city")]      public string City;
  [XmlElement(ElementName="state")]     public State State;
  [XmlElement(ElementName="zip")]       public string Zip;
}

[Serializable]
public class TelephoneNumber {
  [XmlAttribute(AttributeName="type")] public AddressType AddressType;
  [XmlElement(ElementName="areacode")] public string AreaCode;
  [XmlElement(ElementName="exchange")] public string Exchange;
  [XmlElement(ElementName="number")]   public string Number;
}

[Serializable]
public class Employee {
  [XmlAttribute(AttributeName="firstname")]      public string FirstName;
  [XmlAttribute(AttributeName="middleinitial")]  public string MiddleInitial;
  [XmlAttribute(AttributeName="lastname")]       public string LastName;
  
  [XmlArray(ElementName="addresses")]
  [XmlArrayItem(ElementName="address")]      public Address [] Addresses;
  [XmlArray(ElementName="telephones")] 
  [XmlArrayItem(ElementName="telephone")]    public TelephoneNumber [] TelephoneNumbers;
  
  [XmlAttribute(AttributeName="hiredate")]   public DateTime HireDate;
}

[Serializable]
[XmlRoot(ElementName="personnel")]
public class Personnel {
  [XmlElement(ElementName="employee")]
  public Employee [] Employees;
}


           
         
     


This entry was posted in File Stream. Bookmark the permalink.