Read Data from XML File Using C#

07 Jan

Sample XML File

<?xml version="1.0" encoding="utf-8"?>


<Patient id=”1”>






<Patient id=”2”>>







The Code

XmlDocument doc = new XmlDocument();



XmlNodeList patientList = doc.GetElementsByTagName("Patient ");


foreach (XmlNode node in patientList)


XmlElement patientElement = (XmlElement) node;


string first_name = patientElement.GetElementsByTagName("fname")[0].InnerText;

string last_name = patientElement.GetElementsByTagName("lname")[0].InnerText;

string patient_id = "";


if (patientElement.HasAttributes)


patient_id  = patientElement.Attributes["id"].InnerText;



Console.WriteLine("{0} ({1})  {2}\n", first_name, last_name, patient_id);



Posted by on January 7, 2012 in C#.Net, XML


2 responses to “Read Data from XML File Using C#

  1. Abhinav Bindra

    February 29, 2012 at 4:35 pm

    Very nice article. I really enjoyed it reading. And it also cleared lot of my doubts about reading XML file using C# code. You made it very simple and understandable. I would like to appreciate you that keep writing. There is also an article which explained very well on this topic and I was found it at searching time. Check it at once too…

    • Rajitha

      February 29, 2012 at 5:37 pm

      Thank you, Abhinav


Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: