C# XmlDocument SelectNodes is not working

前端 未结 3 553
野的像风
野的像风 2020-12-20 12:27

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

3条回答
  •  温柔的废话
    2020-12-20 13:19

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

提交回复
热议问题