C# XmlDocument SelectNodes无法工作

15

我想从XML文件中获取值,但是我失败了。你能否帮忙指出问题?因为我已经尝试了很长时间的测试和搜索,但仍然无法找到问题。

XML:

<?xml version="1.0" encoding="utf-8" ?> 
<Contacts>
  - <Contact>
    <ID>xxx</ID> 
      <AutoUpdateEnabled>false</AutoUpdateEnabled> 
      <LastChanged>2013-05-29T01:53:59.4470000Z</LastChanged> 
    - <Profiles>
        - <Personal>
              <FirstName>My First Name</FirstName> 
              <LastName>My Last Name</LastName> 
              <UniqueName>My Unique Name</UniqueName> 
              <SortName></SortName> 
              <DisplayName>My Display Name</DisplayName> 
          </Personal>
    </Profiles>
    - <Phones>
        - <Phone>
          <ID>3</ID> 
          <PhoneType>Mobile</PhoneType> 
          <Number>000-0000000</Number> 
          <IsIMEnabled>false</IsIMEnabled> 
          <IsDefault>false</IsDefault> 
          </Phone>
    </Phones>
    - <Locations>
        - <Location>
              <ID>2</ID> 
              <LocationType>Business</LocationType> 
              <CompanyName></CompanyName> 
              <IsDefault>false</IsDefault> 
          </Location>
      </Locations>
</Contact>
- <Contact>
  <ID>xxx</ID> 
  <AutoUpdateEnabled>false</AutoUpdateEnabled> 
  <LastChanged>2013-05-29T01:53:25.2670000Z</LastChanged> 
    - <Profiles>
        - <Personal>
              <FirstName>Person</FirstName> 
              <LastName>Two</LastName> 
              <UniqueName></UniqueName> 
              <SortName></SortName> 
              <DisplayName>Person Two</DisplayName> 
          </Personal>
      </Profiles>
    - <Emails>
        - <Email>
              <ID>1</ID> 
              <EmailType>Personal</EmailType> 
              <Address>MyTest@gmail.com</Address> 
              <IsIMEnabled>false</IsIMEnabled> 
              <IsDefault>true</IsDefault> 
          </Email>
      </Emails>
    - <Locations>
        - <Location>
              <ID>2</ID> 
              <LocationType>Business</LocationType> 
              <CompanyName>Testing Company</CompanyName> 
              <IsDefault>false</IsDefault> 
          </Location>
      </Locations>
    </Contact>
 </Contacts>

我的示例代码:

XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml("TheXMLFile.xml");

xmldoc.DocumentElement.SelectNodes("contact")  // return 0 counts
xmldoc.DocumentElement.SelectNodes("/contact")  // return 0 counts
xmldoc.DocumentElement.SelectNodes("/contact")  // return 0 counts
xmldoc.DocumentElement.SelectNodes("/contacts/contact")  // return 0 counts
xmldoc.DocumentElement.SelectNodes("*")  // return 2 counts  !this works

XmlNodeList elemList = xmldoc.DocumentElement.GetElementsByTagName("contact"); // return 2 counts  !this also works
foreach (XmlNode node in elemList)
{    
    node.SelectSingleNode("Profiles")  //return ""
    node.SelectSingleNode("/Profiles")  //return ""
    node.SelectSingleNode("//Profiles")  //return ""
    node.SelectSingleNode(".//Profiles")  //return ""
}

我只想获取“名字,姓氏,电子邮件地址”,但SelectNodes函数并没有像预期的那样工作...完全没有头绪...请帮帮我。谢谢。

3个回答

14

你需要类似这样的东西:

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;
   }
}

采用这种方法,您应该能够正确地读取所需的所有数据。


我可以在foreach循环中使用“Contact”,然后在循环内选择单个电子邮件吗? - user2402624
@user2402624:如果你只想要一个电子邮件(可能有多个),是的,你可以这样做。 - marc_s
2
我知道这是一篇旧帖,但就我所见,如果您想从XMLNodeList(使用Xpath语句)选择节点,则LoadXML无法工作。我得到了相同的结果-无论如何我排列Xpath都是0。有没有解决这个问题的方法? - MC9000
2
看看这篇文章:https://mymemorysucks.wordpress.com/2007/08/17/xmldocumentselectnodes-selects-nothing/ - Davor
2
指向@Davor-但他不应该只链接到一个页面。虽然与OP的示例无关,但如果XML数据具有命名空间,则SelectNodes需要命名空间管理器才能成功。 - erict

0
问题在于 SelectNodes 方法需要一个区分大小写的 XPath 表达式。
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}");
            }

在上面的代码中,您可以看到两个名字,“My First Name”和“Person”。我只是将第一个字符更改为大写“contact” -> “Contact”。

0

XML标记大小写有区别,所以contact != Contact。

首先更改这个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接