LINQ通过C#XML [英] LINQ to XML via C#
问题描述
我是新来的LINQ。我理解它的目的。但我不能完全弄清楚。我有一个XML集如下所示:
I'm new to LINQ. I understand it's purpose. But I can't quite figure it out. I have an XML set that looks like the following:
<Results>
<Result>
<ID>1</ID>
<Name>John Smith</Name>
<EmailAddress>john@example.com</EmailAddress>
</Result>
<Result>
<ID>2</ID>
<Name>Bill Young</Name>
<EmailAddress>bill@example.com</EmailAddress>
</Result>
</Results>
我已加载这个XML到一个XDocument这样:
I have loaded this XML into an XDocument as such:
string xmlText = GetXML();
XDocument xml = XDocument.Parse(xmlText);
现在,我想要得到的结果为POCO格式。在努力做到这一点,我目前使用的:
Now, I'm trying to get the results into POCO format. In an effort to do this, I'm currently using:
var objects = from results in xml.Descendants("Results")
select new Results
// I'm stuck
我如何通过得到的结果LINQ元素的集合?我特别困惑,在我的代码,这一点导航XML结构。
How do I get a collection of Result elements via LINQ? I'm particularly confused about navigating the XML structure at this point in my code.
感谢您!
推荐答案
这将返回一个的IEnumerable
匿名类的:
This will return a IEnumerable
of anonymous class:
var q = from result in xml.Descendants
select new
{
ID = result.Descendants("ID"),
Name= result.Descendants("Name"),
EmailAddress= result.Descendants("EmailAddress")
};
如果您已经定义的类'结果,例如:
or if you have defined class `Result, e.g.:
class Result
{
public ID { get; set; }
public Name { get; set; }
public EmailAddress { get; set; }
}
然后:
then:
var q = from result in xml.Descendants
select new Result
{
ID = result.Descendants("ID"),
Name = result.Descendants("Name"),
EmailAddress = result.Descendants("EmailAddress")
};
(返回的IEnumerable<结果>
)
这篇关于LINQ通过C#XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!