Saturday, January 7, 2012

Read Data from XML File Using C#

Sample XML File

[sourcecode language="xml"]
<?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>

[/sourcecode]

The Code

[sourcecode language="csharp"]
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);

}

[/sourcecode]

2 comments:

  1. 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

    ReplyDelete

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...