/* @"C:\xml\xml2.xml"
<?xml version="1.0" encoding="utf-8"?>
<food>
<fruits>
<fruit>Apple</fruit>
<fruit>Orange</fruit>
<fruit>Melon</fruit>
<fruit>Watermelon</fruit>
</fruits>
</food>
string xml_path2 = @"C:\xml\xml2.xml";
XDocument doc2 = XDocument.Load(xml_path2);
var 开发者_如何学Cqry2 = doc2.Descendants("fruits").Select(n => n.Element("fruit").Value);
foreach (var item in qry2) {
Console.WriteLine(item);
}
Output: Show only Apple, instead of showing all fruits
I am using Visula Studio 2008 and Net FrameWork 3.5 . Why does it shows like that?
doc2.Descendants("fruits").Select(n => n.Element("fruit").Value);
This will find a single <fruits>
element, it then applies the Element(name)
method to it.
XContainer.Element
is defined (my emphasis):
Gets the first (in document order) child element with the specified XName.
So you get just one result.
精彩评论