我有以下XML檢索元素從XML使用LINQ
<Group>
<Id>2</Id>
<GroupName>Fizzy Drinks</GroupName>
<DateCreated>0001-01-01T00:00:00</DateCreated>
<DateModified>0001-01-01T00:00:00</DateModified>
<Person>
<PersonId>78</PersonId>
<PersonName>Francesca</PersonName>
<PersonSurname>Andrews</PersonSurname>
<PersonAge>59</PersonAge>
</Person>
<Products>
<ProductId>2</ProductId>
<ProductName>Oranges</ProductName>
<CategoryId>4</CategoryId>
<CategoryName></CategoryName>
<SubCategoryId>7</SubCategoryId>
<SubCategoryName>Bread</SubCategoryName>
</Products>
<Products>
<ProductId>12</ProductId>
<ProductName>Pepsi</ProductName>
<CategoryId>4</CategoryId>
<CategoryName></CategoryName>
<SubCategoryId>8</SubCategoryId>
<SubCategoryName>Dairy</SubCategoryName>
</Products>
<Products>
<ProductId>14</ProductId>
<ProductName>Multiwheat Bread</ProductName>
<CategoryId>4</CategoryId>
<CategoryName></CategoryName>
<SubCategoryId>7</SubCategoryId>
<SubCategoryName>Bread</SubCategoryName>
</Products>
</Group>
我希望中檢索組對象中以下。
我有下面的代碼: -
foreach (XElement xe in xdoc.Descendants("Group"))
{
int id = Convert.ToInt32(xe.Element("Id").Value);
var group = from g in xdoc.Descendants("Group")
where (int)g.Element("Id") == id // filtering groups here
select new Group
{
Id = (int)g.Element("Id"),
GroupName = (string)g.Element("GroupName"),
DateCreated = (DateTime)g.Element("DateCreated"),
DateModified = (DateTime)g.Element("DateModified"),
Person = from d in g.Descendants("Person")
select new Person
{
Id = (int)d.Element("PersonId"),
Name = (string)d.Element("PersonName"),
Surname = (string)d.Element("PersonSurname"),
Age = (int)d.Element("PersonAge"),
},
PersonId = (int)g.Element("PersonId"),
PersonName = (string)g.Element("PersonName"),
PersonSurname = (string)g.Element("PersonSurname"),
PersonAge = (int)g.Element("PersonAge"),
Products = g.Elements("Products")
.Select(p => new Product
{
Id = (int)p.Element("ProductId"),
ProductName = (string)p.Element("ProductName")
}).ToList()
};
foreach (var g in group)
{
GroupList.Add(g);
}
}
但是我得到一個錯誤,因爲人不是IEnumerable的。然而,因爲我將只有每個組1人,我不希望使它IEnumerable。有沒有解決的辦法?
感謝您的幫助和時間
感謝喬恩我喜歡這個解決方案! – Johann 2013-03-15 12:04:24