C# XmlDocument SelectNodes is not working

十年热恋 提交于 2019-12-01 15:38:00
marc_s

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".

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!