Hello,

I'm having trouble serilizing different classes to the same xml.

Class #1 is for accounts
Class #2 is for settings

 public static void SerializeAcc(List<Account> list)
        {

            XmlSerializer serializer = new XmlSerializer(typeof(List<Account>), new XmlRootAttribute("Settings"));
            using (TextWriter writer = new StreamWriter(XMLPath))
            {
                serializer.Serialize(writer, list);
            }
        }
        public static void SerializeSett(List<General> list)
        {

            XmlSerializer serializer = new XmlSerializer(typeof(List<General>), new XmlRootAttribute("Settings"));
            using (TextWriter writer = new StreamWriter(XMLPath))
            {
                serializer.Serialize(writer, list);
            }
        }

And when I call one it would look like:

<Setting>
<Account>
infohere
</Account>
</Setting>

and when I call the other one instead of putting the info below any account it just replaces it to:

<Setting>
<General>
infohere
</General>
</Setting>

Im trying to accomplish to save both acocunts and settings into the same xml like so:

<Setting>
<Account>
infohere
</Account>
<Account>
infohere
</Account>
<Account>
infohere
</Account>
<General>
infohere
</General>
</Setting>

It can be infinite amount of accounts, but only 1 "General" (Settings) on the bottom.

Edited 3 Years Ago by iFrolox

First thing I noticed is that you accept a list of type General but you say you only want a single instance. I suggest you change that method to only take a single object.

Additionally, as you're going to be working with an existing XML set, it might be worthwhile using an XmlDocument or XDocument class so that it's easier to work with and modify the node-set.
An additional advantage of using these objects is that you can query them with XPath.

Finally, unless you want all the class and library metadata, I wouldn't bother using the built in XmlSerializer but instead pull each setting out manually. I understand that the serialiser is easier, however, you lost a lot of control by using it.

Edited 3 Years Ago by Ketsuekiame

Im trying to accomplish to save both aco####s and settings into the same xml like so

Then if you want to continue using XmlSerializer, you should wrap those two classes in a another class, then serialize that one:

class AppSettings
{
    public General GeneralSettings { get; set; }
    public List<Account> Accounts { get; set; }
}

XmlSerializer treats the entire class hierarchy as a single self-contained XML entity, which means the highest level class is your XML root.

Comments
Oh, thank you!
This question has already been answered. Start a new discussion instead.