RSS

Read Data from XML File Using C#

07 Jan

Sample XML File

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

<PatientInfo>

<Patient id=”1”>

<app-no>03</app-no>

<fname>Brian</fname>

<lname>Marsh</lname>

<docId>03</docId>

</Patient>

<Patient id=”2”>>

<app-no>02</app-no>

<fname>Bron</fname>

<lname>Marini</lname>

<docId>01</docId>

</Patient>

</PatientInfo>

The Code

XmlDocument doc = new XmlDocument();

doc.Load("files/sampleXML.xml");

&nbsp;

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

&nbsp;

foreach (XmlNode node in patientList)

{

XmlElement patientElement = (XmlElement) node;

&nbsp;

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

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

string patient_id = "";

&nbsp;

if (patientElement.HasAttributes)

{

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

}

&nbsp;

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

}

Advertisements
 
2 Comments

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…

    http://mindstick.com/Articles/851bfc02-9c84-41c4-a3ca-d83b5fd0adf2/?How%20to%20read%20data%20from%20XML%20file%20in%20C%20Sharp

     
    • 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:

WordPress.com Logo

You are commenting using your WordPress.com 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: