.NET: Iterate Over an XML File and a List of Nodes

10/18/2015 6:52:46 PM

The following will open an XML file and iterate over a list of nodes.

string xmlFile = System.IO.Path.Combine(path, "UserList.xml");
if (System.IO.File.Exists(symbolFile))
	System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
	System.Xml.XmlElement root = xmlDoc.DocumentElement;
	System.Xml.XmlNodeList nodeList = root.SelectNodes("User");

	foreach (System.Xml.XmlNode node in nodeList)
		var attributes = node.Attributes;
		string firstName = attributes.GetNamedItem("FirstName").Value;
		string lastName = attributes.GetNamedItem("LastName").Value;

		//do something

/////sample xml
<?xml version="1.0" encoding="utf-8"?>
<AllUsers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <User FirstName="John1" LastName="Doe1" />
  <User FirstName="John2" LastName="Doe2" />
  <User FirstName="John3" LastName="Doe3" />
  <User FirstName="John4" LastName="Doe4" />