This prior post detailed how to write to an XML file. This post details how to read that XML file.
The example reads the values and populates three TextBoxes, but you can use this technique to read any information from an XML file.
XML File:
<?xml version="1.0" encoding="utf-8"?>
<Employee>
<LastName>Baggins</LastName>
<FirstName>Bilbo</FirstName>
<PhoneNumber>(925)555-1234</PhoneNumber>
</Employee>
In C#:
var doc = XDocument.Load("Employee.xml");
var emp = doc.Descendants("Employee").FirstOrDefault();
textBox1.Text = emp.Element("LastName").Value;
textBox2.Text = emp.Element("FirstName").Value;
textBox3.Text = emp.Element("PhoneNumber").Value;
In VB:
Dim doc = XDocument.Load("Employee.xml")
Dim emp = doc.Descendants("Employee").FirstOrDefault()
TextBox1.Text = emp.Element("LastName").Value
TextBox2.Text = emp.Element("FirstName").Value
TextBox3.Text = emp.Element("PhoneNumber").Value
In VB using XML Literals:
Dim doc = XDocument.Load("Employee.xml")
TextBox1.Text = doc...<LastName>.Value
TextBox2.Text = doc...<FirstName>.Value
TextBox3.Text = doc...<PhoneNumber>.Value
This code first loads the XML file into an XML document.
In the first two examples, the code finds the first Employee node. In this case, there is only one. It then uses the Element function to retrieve the defined element ("LastName", "FirstName", and "PhoneNumber") from the Employee node. The Value property provides the string value of the element. This value is assigned to the TextBox.
The third example above uses XML literals to retrieve the elements from the XML document. The "..." syntax denotes to search any descendants, so the Employee node does not have to be found first.
Use one of the above techniques any time you need to read values from an XML file.
Enjoy!