0

So I just want to build simple app in WPF for managing invoices in my company, but without SQL database.

I decided to use XML format. But whenever I try to save data to my created XML file, the previous data is being overwritten. I tried to use docs example, but again data has been overwritten. Don't know why but i can store only one instance of my class(one company). I tried also putting companies into List and the adding to the xml file, still not working.

Anyone have any ideas how to resolve this problem?

My klass company

public class Company()
{
        public int Id_company;
        public string Name_Company;


        public void add_Company(int id_company, string name_company)
        {
            this.Id_company = id_company;
            this.Name_Company = name_company;
        }
    }
}

Saving to XML tried to assign to a button in app

 private void Button_Click(object sender, RoutedEventArgs e)
        {
            Company company1 = new Company();
            company1.add_Company(1, "Company1");
        
            System.Xml.Serialization.XmlSerializer writer =
                new System.Xml.Serialization.XmlSerializer(typeof(Company));

           
            System.IO.FileStream file = System.IO.File.Create(path);

            writer.Serialize(file, company1);
            file.Close();
            writer.Serialize;
        }
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • The way you are doing this, it will always rewrite the file, even assuming you'll change IO.File.Create. You should first read the current file into the object, update it and save it into the file – ASpirin Dec 07 '20 at 07:29
  • You can't just overwrite data in any text file, much less an XML file. When you write in the middle of a file you write a specific number of bytes, not lines. If you write less data, you'll leave old data behind. If you write too much, you overwrite other data. You can only append text, but that would produce an invalid XML file (JSON has the same problem). You *have* to read the entire XML document, modify it and write it back – Panagiotis Kanavos Dec 07 '20 at 07:41
  • This is typically done in a variety of ways. The two simplest approaches: 1) keep the DOM around, adding a node each time you want to save it; 2) read the DOM from the XML each time, add the node, then write again. See duplicates for more elaborate solutions that are more efficient but also harder to implement and maintain. – Peter Duniho Dec 07 '20 at 07:42
  • In log-like files, it's common to store one unindented XML or JSON line per record, which allows adding new records by appending lines. The overall file isn't valid XML or JSON, but reading individual rows is easy. It's possible to start reading from the middle of the file, by starting at a position and reading forwards or backwards until a newline is encountered – Panagiotis Kanavos Dec 07 '20 at 07:45

0 Answers0