您的代码实际上有效:
static void Main(string[] args)
{
string xml = @"
<Items>
<Item>
<Stuff>Strings</Stuff>
</Item>
<Item>
<Stuff>Strings</Stuff>
</Item>
</Items>";
using (StringReader myStream = new StringReader(xml))
{
XDocument doc = XDocument.Load(myStream);
var query = from node in doc.Descendants(XName.Get("Item"))
select new { Stuff =
node.Element(XName.Get("Stuff")).Value };
foreach (var item in query)
{
Console.WriteLine("Stuff: {0}", item.Stuff);
}
}
应该注意的是,如果元素没有使用命名空间限定,那么您实际上并不需要 XName:
static void Main(string[] args)
{
string xml = @"
<Items>
<Item>
<Stuff>Strings</Stuff>
</Item>
<Item>
<Stuff>Strings</Stuff>
</Item>
</Items>";
using (StringReader myStream = new StringReader(xml))
{
XDocument doc = XDocument.Load(myStream);
var query = from node in doc.Descendants("Item")
select new { Stuff = node.Element("Stuff").Value };
foreach (var item in query)
{
Console.WriteLine("Stuff: {0}", item.Stuff);
}
}
}