I am trying to get familiar with using the XDocument API to parse XML using the lambda syntax.
What I would like to do is create a IEnumerable list of Product based on the following XML structure. I know how to get all of the product nodes but I want to get each of the product nodes name attribute and then select each item node from within the ‘product’ node and parse it for its values.
So I want to take this XML:
<products>
<product name="Prod1">
<item hwid="abk9184">
<href>Prod1/abk9184_en-us/abk9184.html</href>
<localization>en-us</localization>
<build.start>2011-06-08 22:02 PM</build.start>
<build.icp>9.0.192.32</build.icp>
</item>
<item hwid="abk9185">
<href>Prod1/abk9185_en-us/abk9185.html</href>
<localization>en-us</localization>
<build.start>2011-06-08 22:03 PM</build.start>
<build.icp>9.0.192.32</build.icp>
</item>
</product>
<product name="Prod2">
<item hwid="aa6410">
<href>Prod2/aa6410_en-us/aa6410.html</href>
<localization>en-us</localization>
<build.start>2011-06-08 22:04 PM</build.start>
<build.icp>9.0.192.32</build.icp>
</item>
</product>
</products>
And from it I would like to get a list of these:
public class Product
{
public string Name { get; set; }
public string Hwid { get; set; }
public string Href { get; set; }
public string Localization { get; set; }
public DateTime BuildDateTime { get; set; }
public string IcpBuildVersion { get; set; }
}
So although I have 2 product nodes I would end up with many product instances of each. I’d like to learn how to do this using the XDocument and the lambda syntax. Can someone show me the way?
IEnumerable<Product> products = xDocument.Decendants("product")
.Select(e => new Product { Name = e.Name })
But think there would have to be some looping here to get each item from each product.
1 Answer