I would like to loop through following collection of authors and for each author retrieve its first and last name and put them in a variable strFirst and strLast?
<Authors>
<Author>
<FirstName>Jon</FirstName>
<LastName>Doe</LastName>
</Author>
<Author>
<FirstName>Shahzad</FirstName>
<LastName>Khan</LastName>
</Author>
</Authors>
We’ll use XmlDocument class to parse this XML fragment;
using System;
using System.Xml;
public class XMLApp
{
public void YourMethod(String strFirst, String strLast)
{
// Do something with strFirst and strLast.
// ...
Console.WriteLine("{0}, {1}", strLast, strFirst);
}
public void ProcessXML(String xmlText)
{
XmlDocument _doc = new XmlDocument();
_doc.LoadXml(xmlText);
// alternately, _doc.Load( _strFilename); to read from a file.
XmlNodeList _fnames = _doc.GetElementsByTagName("FirstName");
XmlNodeList _lnames = _doc.GetElementsByTagName("LastName");
// I'm assuming every FirstName has a LastName in this example, your requirements may vary. //
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();
// Passing XML text as a String, you can also use the
// XMLDocument::Load( ) method to read the XML from a file.
//
_app.ProcessXML(@" <Authors>
<Author>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
</Author>
<Author>
<FirstName>Shahzad</FirstName>
<LastName>Khan</LastName>
</Author>
</Authors> ");
}
}// end XMLApp
}
Resources
https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmldocument?view=net-7.0
Add to favorites