C# XmlDocument SelectNodes is not working

前端 未结 3 540
野的像风
野的像风 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:10

    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.

    0 讨论(0)
  • 2020-12-20 13:17

    The XML tags are case dependent so contact != Contact.

    Change this for a start.

    0 讨论(0)
  • 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".

    0 讨论(0)
提交回复
热议问题