从具有相同名称的节点获取值

我想从XML文件中检索信息,但是它的格式化方式非常奇怪。 这里是…

       Cook Cooks food for people   

我想得到第二个值,这将是库克和人们烹饪食物的描述,但我得到的只是空节点。 例如…

  public string CareerDescription(string CareerFile) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(CareerFile); string Description = xmlDoc.SelectSingleNode("Careers/CareerList/CareerDescription").InnerText; return Description; } 

我如何选择第二个节点而不是第一个节点?

您可以在XPath表达式中使用索引:

 xmlDoc.SelectSingleNode("Careers/CareerList[2]/CareerDescription").InnerText 

就个人而言,我会使用LINQ to XML,请注意:

 var doc = XDocument.Load(CareerFile); return doc.Root .Elements("CareerList") .ElementAt(1) // 0-based .Element("CareerDescription") .Value; 

您应该使用SelectNodes而不是SelectSingleNode :它将返回XmlNodeList nodeList 。 然后你应该从索引[1]的节点列表中获取元素的InnerText ;

 public string CareerDescription(string CareerFile) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(CareerFile); string Description = xmlDoc.SelectNodes("Careers/CareerList/CareerDescription")[1].InnerText; return Description; } 

有关更多详细信息,请参阅MSDN上有关此方法的文档: http : //msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes%28v=vs.71%29.aspx

只是LINQ to XML例程的直接方式(因为它是LINQ,我更喜欢这种方式,而不是XathDocument的“标准”用法,并且支持XPath):

 return XDocument.Load(CareerFile) .Descendants("CareerDescription").Skip(1).First().Value;