Suppose I have following XML fragment
- <Authors>
- <Author>
- <FirstName>John</FirstName>
- <LastName>Doe</LastName>
- </Author>
- <Author>
- <FirstName>Jane</FirstName>
- <LastName>Eod</LastName>
- </Author>
- </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
- using System;
- using System.Xml;
- public class XMLApp
- {
- public void YourMethod(String strFirst, String strLast)
- {
-
-
- Console.WriteLine("{0}, {1}", strLast, strFirst);
- }
- public void ProcessXML(String xmlText)
- {
- XmlDocument _doc = new XmlDocument();
- _doc.LoadXml(xmlText);
-
- XmlNodeList _fnames = _doc.GetElementsByTagName("FirstName");
- XmlNodeList _lnames = _doc.GetElementsByTagName("LastName");
-
- for (int _i = 0; _i < _fnames.Count; ++_i)
- {
- YourMethod(_fnames[_i].InnerText,
- _lnames[_i].InnerText);
- }
- public static void Main(String[] args)
- {
- XMLApp _app = new XMLApp();
-
-
-
- _app.ProcessXML(@" <Authors>
- <Author>
- <FirstName>John</FirstName>
- <LastName>Doe</LastName>
- </Author>
- <Author>
- <FirstName>Jane</FirstName>
- <LastName>Eod</LastName>
- </Author>
- </Authors> ");
- }
- }
- }
Remember to reference the System.Xml.dll on the command-line to build XMLApp.cs:
csc.exe /r:System.Xml.dll XMLApp.cs