我正在尝试熟悉使用XDocument
API来使用lambda语法解析XML。
我想要做的是根据以下XML结构创建IEnumerable
Product
列表。我知道如何获取所有product
个节点,但我想获取每个产品节点name
属性,然后从“产品”节点中选择每个item
节点并解析它因为它的价值观。
所以我想采用这个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>
从中我想得到一份清单:
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; }
}
因此,虽然我有2个产品节点,但最终会有很多产品实例。我想学习如何使用XDocument
和lambda语法来完成这项工作。有人能给我指路吗?
IEnumerable<Product> products = xDocument.Decendants("product")
.Select(e => new Product { Name = e.Name })
但是认为必须有一些循环才能从每个产品中获取每个项目。
答案 0 :(得分:1)
var products = document.Descendants("item")
.Select(arg =>
new Product
{
Name = arg.Parent.Attribute("name").Value,
Hwid = arg.Attribute("hwid").Value,
Href = arg.Element("href").Value,
Localization = arg.Element("localization").Value,
BuildDateTime = DateTime.Parse(arg.Element("build.start").Value),
IcpBuildVersion = arg.Element("build.icp").Value
})
.ToList();