How to save data from a Windows form to an XML file?

I'm pretty sure I need to create some form from which the XML file should look like, right?

Any help would be appreciated.

+3
source share
3 answers

One easy way to do this is to create the .NET classes in which you put the data, and then use the XmlSerializer to serialize the data to a file, and then deserialize it back to the class instance and re-fill the form.

, . , . . , : / , .

public class CustomerData
{
  public string FirstName;
  public string LastName;
}

, XML, .

// Create an instance of the CustomerData class and populate
// it with the data from the form.
CustomerData customer = new CustomerData();
customer.FirstName = txtFirstName.Text;
customer.LastName = txtLastName.Text;

// Create and XmlSerializer to serialize the data to a file
XmlSerializer xs = new XmlSerializer(typeof(CustomerData));
using (FileStream fs = new FileStream("Data.xml", FileMode.Create))
{
  xs.Serialize(fs, customer);
}

:

CustomerData customer;
XmlSerializer xs = new XmlSerializer(typeof(CustomerData));
using (FileStream fs = new FileStream("Data.xml", FileMode.Open))
{
  // This will read the XML from the file and create the new instance
  // of CustomerData
  customer = xs.Deserialize(fs) as CustomerData;
}

// If the customer data was successfully deserialized we can transfer
// the data from the instance to the form.
if (customer != null)
{
  txtFirstName.Text = customer.FirstName;
  txtLastName.Text = customer.LastName;
}
+11
0

Source: https://habr.com/ru/post/1746460/


All Articles