I have a method that executes upon form_load event that seems to work properly omitting one line.
private int ReadInPeople()
{
XmlNodeList nodeList = m_xmlDoc.DocumentElement.ChildNodes;
foreach (XmlNode PersonNode in nodeList)
{
Employee ccontact = new Employee();
foreach (XmlNode PersonTag in PersonNode.ChildNodes)
{
switch (PersonTag.Name)
{
case "Employee":
ccontact.EmployeeNumber = PersonTag.FirstChild.Value;
break;
case "FirstName":
ccontact.FirstName = PersonTag.FirstChild.Value;
break;
case "LastName":
ccontact.LastName = PersonTag.FirstChild.Value;
break;
default:
break;
}
}
this.AddContact(ccontact);
}
return nodeList.Count;
}
The AddContact method adds the Employee object to a static list; however, the line:
this.AddContact(ccontact);
was not being executed.
A sample of the XML file:
<?xml version="1.0" encoding="utf-8"?>
<people>
<person>
<Employee>123456789</Employee>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</person>
<person>
<Employee>987654321</Employee>
<FirstName>Ellen</FirstName>
<LastName>Wayne</LastName>
</person>
</people>
I had tried setting a breakpoint and debugging, and sure enough, the line was skipped over completely as if it were not even there.
As per Alan’s advice, I changed the PersonTag.FirstChild.Value as it was attempting to reference a ChildNode that did not exist.
The updated, working method:
private int ReadInPeople()
{
XmlNodeList nodeList = m_xmlDoc.DocumentElement.ChildNodes;
foreach (XmlNode PersonNode in nodeList)
{
Employee ccontact = new Employee();
foreach (XmlNode PersonTag in PersonNode.ChildNodes)
{
switch (PersonTag.Name)
{
case "Employee":
ccontact.EmployeeNumber = PersonTag.InnerText;
break;
case "FirstName":
ccontact.FirstName = PersonTag.InnerText;
break;
case "LastName":
ccontact.LastName = PersonTag.InnerText;
break;
default:
break;
}
}
this.AddContact(ccontact);
}
return nodeList.Count;
}
You can easily parse your xml with LINQ to XML:
XmlDocument solution: