2012-08-06 64 views
0

当没有更多孩子时,如何在XDocument中获得Node的价值?获取没有孩子的XElements的价值

<Contacts> 
     <Company> 
      <Name>Testing</Name> 
      <ID>123</ID> 
     </Company> 
</Contacts> 

在这种情况下,我想拿到<Name><ID>元素的值,因为没有在他们的子元素。

我想后续

protected void LeXMLNode(HttpPostedFile file) 
{ 
    XmlReader rdr = XmlReader.Create(file.FileName);    
    XDocument doc2 = XDocument.Load(rdr);    

    foreach (var name in doc2.Root.DescendantNodes().OfType<XElement>().Select(x => x.Name).Distinct()) 
    { 
     XElement Contact = (from xml2 in doc2.Descendants(name.ToString())          
          where xml2.Descendants(name.ToString()).Count() == 0 
          select xml2).FirstOrDefault(); 

     string nome = name.ToString(); 
    }   
} 

但没有成功,因为我的foreach传中所有Elements,我想获得做到这一点不是有孩子的的的Elements值。

+0

一旦你的姓名和ID的元素,你应该使用的XElement的Value属性检索元素文本http://msdn.microsoft.com/en-us/library /system.xml.linq.xelement.value.aspx – 2012-08-06 20:46:18

回答

1
document.Root.Elements("Company").Elements() 
       .Where(item => !item.HasElements).ToList();