我有以下 XML
<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>
我希望在 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);
}
}
但是我收到一个错误,因为 Person 不是 IEnumerable。但是,由于我每组只有 1 人,因此我不希望将其设为 IEnumerable。有没有解决的办法?
感谢您的帮助和时间