Reading XML File using XmlDocument

In this article Reading XML File using XmlDocument.

Suppose I have following XML fragment

  1. <Authors>  
  2. <Author>  
  3. <FirstName>John</FirstName>  
  4. <LastName>Doe</LastName>  
  5. </Author>  
  6. <Author>  
  7. <FirstName>Jane</FirstName>  
  8. <LastName>Eod</LastName>  
  9. </Author>  
  10. </Authors>  
Now, how can I loop through my collection of authors and for each author  retrieve its first and last name and put them in a variable strFirst and  strLast?

XMLApp.cs

  1. using System;    
  2. using System.Xml;    
  3. public class XMLApp    
  4. {    
  5.     public void YourMethod(String strFirst, String strLast)    
  6.     {    
  7.         // Do something with strFirst and strLast.    
  8.         // ...    
  9.         Console.WriteLine("{0}, {1}", strLast, strFirst);    
  10.     }    
  11.     public void ProcessXML(String xmlText)    
  12.     {    
  13.         XmlDocument _doc = new XmlDocument();    
  14.         _doc.LoadXml(xmlText);    
  15.         // alternately, _doc.Load( _strFilename); to read from a file.    
  16.         XmlNodeList _fnames = _doc.GetElementsByTagName("FirstName");    
  17.         XmlNodeList _lnames = _doc.GetElementsByTagName("LastName");    
  18.         // I'm assuming every FirstName has a LastName in this example, your requirements may vary. //     
  19.         for (int _i = 0; _i < _fnames.Count; ++_i)    
  20.         {    
  21.             YourMethod(_fnames[_i].InnerText,    
  22.             _lnames[_i].InnerText);    
  23.         }    
  24.         public static void Main(String[] args)    
  25.         {    
  26.             XMLApp _app = new XMLApp();    
  27.             // Passing XML text as a String, you can also use the    
  28.             // XMLDocument::Load( ) method to read the XML from a file.    
  29.             //    
  30.             _app.ProcessXML(@" <Authors>    
  31.             <Author>    
  32.             <FirstName>John</FirstName>    
  33.             <LastName>Doe</LastName>    
  34.             </Author>    
  35.             <Author>    
  36.             <FirstName>Jane</FirstName>    
  37.             <LastName>Eod</LastName>    
  38.             </Author>    
  39.             </Authors> ");    
  40.         }    
  41.     }// end XMLApp    
  42. }  

Remember to reference the System.Xml.dll on the command-line to build XMLApp.cs:

csc.exe /r:System.Xml.dll XMLApp.cs