title: How to serialize and deserialize hierarchical class as xml in C#?
body: <p>Actually I could serialize but i couldn't deserialize it. I need to have an object of my viewmodel with all children from output of destabilization and also i'm not sure where i should set my xml attributes; model or view model.</p>
  
  <p>Here's my clss and viewmodel</p>
  
  <pre><code>public class Person
  {
       public string Name { get; set; }       
       readonly List&lt;Person&gt; children = new List&lt;Person&gt;();
       public IList&lt;Person&gt; Children
       {
           get { return children; }
       }    
  }
  
  public class PersonViewModel : {
  
  private ObservableCollection&lt;PersonViewModel&gt; children; 
  private Person person;
  
  public PersonViewModel()
  {
      person = new Person();
  }
  
  public PersonViewModel(Person _person)
  {
      person = _person;
      children = new ObservableCollection&lt;PersonViewModel&gt;(
              (from child in _person.Children
                  select new PersonViewModel(child))
                  .ToList&lt;PersonViewModel&gt;());
  }
  
  [XmlElement("Name", typeof(string))]
  public string Name
  {
      get
      {
          return person.Name;
      }
  
      set
      {
          person.Name = value;
          this.RaisePropertyChanged("Name");
      }
  }
  
  [XmlArray("Children", IsNullable = false), XmlArrayItem("Person"),]
  public ObservableCollection&lt;PersonViewModel&gt; Children
  {
      get
      {
          return children;
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>this is the content of xml file that my code generated already.
  but when i want to deserilize it to an object type of my view model, the children won't initialized by existing data.</p>
  
  <p><img src="https://i.stack.imgur.com/RlWGm.jpg" alt="enter image description here"></p>
  
  <p>Serializer:</p>
  
  <pre><code>            XmlSerializer xs = new XmlSerializer(typeof(PersonViewModel), new XmlRootAttribute { ElementName = "OrgChart" });
          using (StreamWriter wr = new StreamWriter(System.AppDomain.CurrentDomain.BaseDirectory + "OrgChart.XML"))
          {
              xs.Serialize(wr, rootPerson);
          }
  </code></pre>
  
  <p>Deserializer:</p>
  
  <pre><code>                    XmlSerializer xs = new XmlSerializer(typeof(PersonViewModel), new XmlRootAttribute { ElementName = "OrgChart" });
  
                  FileStream fs = new FileStream(filePath, FileMode.Open);
                  XmlReader reader = XmlReader.Create(fs);
  
                  rootPerson = SelectedItem = Profile = (PersonViewModel)xs.Deserialize(reader);
                  reader.Close();
  </code></pre>