LINQ to XML via C#

2019-05-03 07:48发布

问题:

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>

I have loaded this XML into an XDocument as such:

string xmlText = GetXML();
XDocument xml = XDocument.Parse(xmlText);

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

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.

Thank you!

回答1:

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")
        };

(returns IEnumerable<Result>)



回答2:

If your Results child elements are only Result elements, then you can get them like this:

var objects = from result in xml.Descendants
              select result;

But in this lucky case you can just use xml.Descendants.

If it's not only Result elements, then this will do fine:

var object = from result in xml.Descendants
             where result.Name == "Result"
             select result;


回答3:

If you are new to LINQ, you will also find extremely useful links in this question