-1

I have a class and i need to save this class into an XML file. Since i have more objects from this class i need every object to be added under the same root.

I start out with the xml file as this:

<?xml version="1.0" encoding="utf-8"?>
<root>
</root>

My class looks like this:

class Save
{
 string a;
 string b;
 List<subClass> L1;
 List<subClass> L2;


 subClass 
 {
  string c;
  double d;
 }
}

The xml file after saveing should look like this:

<?xml version="1.0" encoding="utf-8"?>
<root>
 <object>
  <Element1>a</Element1>
  <Element2>b</Element2>
  <objectListL1>
   <Element3>c</Element3>
   <Element4>d</Element4>
  </objectListL1>
  ...
  <objectListL2>
   <Element3>c</Element3>
   <Element4>d</Element4>
  </objectListL2>
  ...
 </object>
</root>

Of course objectListL1 and objectListL2 are repeated as often as entries in the List are found. I just want to create a class, fill it with all my data and than do class.Save() and it should add a new object entry to my XMLfile.

Hunselfunsel
  • 329
  • 1
  • 3
  • 15
  • 2
    Using the [XMLSerializer](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx), isn't an option? – Odrai Dec 09 '17 at 14:27
  • 2
    Possible duplicate of [Serialize an object to XML](https://stackoverflow.com/questions/4123590/serialize-an-object-to-xml) – Odrai Dec 09 '17 at 14:29

1 Answers1

2

I think i found an easy solution:

XmlSerializer serializer = new XmlSerializer(typeof(CLASSNAME));
            StreamWriter sw = File.AppendText(FILEPATH);
            using (sw)
            {
                serializer.Serialize(sw, OBJECT);
            }

This will create a file FILEPATH and serialize everything into it. SInce it is with "AppendText" it can be used with a list ob onjects!

If appending is not needed, instead of the Streamwriter one can use:

using (TextWriter writer = new StreamWriter(FILEPATH))
Hunselfunsel
  • 329
  • 1
  • 3
  • 15
  • If the file was not empty, then because of the `AppendText` will add data to the file. How then to read them out? Use `Create*` or `Open*` methods instead. Using `new StreamWriter` or `new FileStream` is good solution too. – Alexander Petrov Dec 09 '17 at 15:59