xml – C# XmlDocument SelectNodes is not working
xml – C# XmlDocument SelectNodes is not working
You need something like this:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(@D:tempcontacts.xml); // use the .Load() method - not .LoadXml() !!
// get a list of all <Contact> nodes
XmlNodeList listOfContacts = xmldoc.SelectNodes(/Contacts/Contact);
// iterate over the <Contact> nodes
foreach (XmlNode singleContact in listOfContacts)
{
// get the Profiles/Personal subnode
XmlNode personalNode = singleContact.SelectSingleNode(Profiles/Personal);
// get the values from the <Personal> node
if (personalNode != null)
{
string firstName = personalNode.SelectSingleNode(FirstName).InnerText;
string lastName = personalNode.SelectSingleNode(LastName).InnerText;
}
// get the <Email> nodes
XmlNodeList emailNodes = singleContact.SelectNodes(Emails/Email);
foreach (XmlNode emailNode in emailNodes)
{
string emailTyp = emailNode.SelectSingleNode(EmailType).InnerText;
string emailAddress = emailNode.SelectSingleNode(Address).InnerText;
}
}
With this approach, you should be able to read all the data you need properly.
The XML tags are case dependent so contact != Contact.
Change this for a start.
xml – C# XmlDocument SelectNodes is not working
The issue is that SelectNodes method takes a XPath expression that is case sensitive.
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(TheXMLFile.xml);
Console.WriteLine($Contact: {xmldoc.DocumentElement.SelectNodes(Contact).Count}); // return 2
Console.WriteLine($/Contact: {xmldoc.DocumentElement.SelectNodes(/Contact).Count}); // return 0, and it is the expected!
Console.WriteLine($//Contact: {xmldoc.DocumentElement.SelectNodes(//Contact).Count}); // return 2
foreach (XmlNode firstName in xmldoc.DocumentElement.SelectNodes(//Profiles/Personal/FirstName))
{
Console.WriteLine($firstName {firstName.InnerText});
}
In the code above you can see 2 first names, My First Name and Person. I just change the first char to upper case contact -> Contact.