Sometimes, you just need to write some values to an XML file. If you are targeting the .NET Framework 3.5 or higher, you can use XDocument and XElement to do this easily.
This post demonstrates how to write values to an XML string. The example writes the values from three TextBoxes, but you can use this technique to write any information to an XML file.
In C#:
var doc = new XDocument();
var emp = new XElement("Employee");
emp.Add(new XElement("LastName", textBox1.Text));
emp.Add(new XElement("FirstName", textBox2.Text));
emp.Add(new XElement("PhoneNumber", textBox3.Text));
doc.Add(emp);
doc.Save("Employee.xml");
In VB:
Dim doc = New XDocument()
Dim emp = New XElement("Employee")
emp.Add(New XElement("LastName", TextBox1.Text))
emp.Add(New XElement("FirstName", TextBox2.Text))
emp.Add(New XElement("PhoneNumber", TextBox3.Text))
doc.Add(emp)
doc.Save("Employee.xml")
In VB using XML Literals:
Dim doc = New XDocument()
Dim emp = <Employee>
<LastName><%= TextBox1.Text %></LastName>
<FirstName><%= TextBox2.Text %></FirstName>
<PhoneNumber><%= TextBox3.Text %></PhoneNumber>
</Employee>
doc.Add(emp)
doc.Save("Employee.xml")
This code first creates a new XDocument that defines the XML document.
In the first two examples, the code then creates a new XElement defining the root node of the XML string. In this case, the root node is "Employee", but it can be anything.
The sub elements are then added to the Employee root element. In this case, the sub elements are "LastName", "FirstName", and "PhoneNumber" and the values of these elements come from the TextBoxes.
The third example above uses XML literals to perform the same operation. It builds the XML string using the <%= %> replacement syntax to populate the value of each element.
In each example, the new Employee element is then added to the XML document and saved.
The resulting XML file is shown below.
XML File:
<?xml version="1.0" encoding="utf-8"?>
<Employee>
<LastName>Baggins</LastName>
<FirstName>Bilbo</FirstName>
<PhoneNumber>(925)555-1234</PhoneNumber>
</Employee>
(See this post for information on reading the above XML file.)
Use one of the above techniques any time you need to write values to an XML file.
Enjoy!
EDIT 6/7/10: To write XML documents that include attributes, see this other post.