I want to get the value from XML file but I failed. Can you please help me point out the problem ?? Because I already tried very hard to test and googling but I still can\'t
You need something like this:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(@"D:\temp\contacts.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.
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".