Sample : Reading an XML File Using LINQ


This prior post detailed how to write to an XML file. This one is about how to read that XML file.

You need to add using System.Xml.Linq Name space in the C# code
Sample XML:



<?xml version="1.0" encoding="utf-8"?> 
<UserInfo> 
  <LastName>Joseph</LastName> 
  <FirstName>Soumya</FirstName> 
  <PhoneNumber>(000)555-1234</PhoneNumber> 
</<UserInfo> 

This code first loads the XML file into an XML document.Source code is given below



var doc = XDocument.Load("UserInfo.xml");

var userInfo= doc.Descendants("UserInfo").FirstOrDefault();

textBox1.Text = userInfo.Element("LastName").Value; 
textBox2.Text = userInfo.Element("FirstName").Value; 
textBox3.Text = userInfo.Element("PhoneNumber").Value;

The code finds the first UserInfo 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 UserInfo node. The Value property provides the string value of the element. This value is then assigned to the TextBox.

HappyCoding ! 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: