Reading an XML File
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!
Rostov — June 7, 2010 @ 2:06 pm
Just a word of caution:
remember that using an XDocument for your loading starts your ‘search’ at the document declaration and not your actual root node of ‘data’.
In this case because you’re using ‘descendants’ you’re fine — but if you weren’t, (and if you don’t need to use the document declaration for anything) using an XElement.Load works fine.
And also be careful to note the distinction between ‘.Elements’ and ‘.Descendants’ — where the former returns the elements that match the current location/node you are on, and where Descendants matches any and ALL nodes with that name regardless of their nesting level into or below your current location.
DeborahK — June 7, 2010 @ 6:57 pm
Thanks for the tips, Rostov!
Jeannie — June 30, 2011 @ 4:25 am
Wham bam thank you, maam, my qeuisotns are answered!
Luke Pammant — September 7, 2012 @ 8:41 am
Great tips! This is just what I was looking for. Short and to the point.