views:

303

answers:

3

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?

+6  A: 

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

Darin Dimitrov
this is also the preferred default mechanism for serialisation now in the absence of compelling reasons for the older mechanisms.
ShuggyCoUk
Your DataContractSerializer link links to XmlSerializer in MSDN...
configurator
@configurator, thanks for pointing this. I edited my post accordingly.
Darin Dimitrov
I'd post the finished code if I had more than 300 characters to play with, but suffice to say, using the DataContractSerializer worked. Thank you.
Stuart Whiteford
A: 

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.

John Saunders
A: 

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;
  }
}
Serge - appTranslator