Question

I can't seem to get this working, here is my (stripped down) code: -

[XmlRoot("report")]
public class Report
{
    [XmlArray("sections"), XmlArrayItem("section")]
    public List<Section> Sections;
}

public class Section
{
    public Report Report;
}

Am I missing something?

Was it helpful?

Solution

Your objects contain circular references which is not supported by the XmlSerializer class. You could instead look at the DataContractSerializer which supports such scenarios.

OTHER TIPS

You should make sure you know how you want those classes to serialize and deserialize. Write the XML you want as a result, and figure out how you want objects to become XML and vice versa. It's not a no-brainer.

Here's my solution. It might not be as elegant as you'd expect:

public class Report
{
  //...


  void PostLoad()
  {
    foreach(Section s in Sections)
    {
      s.Report = this;
    }
  }

  public static Report Load(string filename)
  {
    // Load using an XmlSerializer
    Report report = ...;

    report.PostLoad();

    return report;
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top