Reputation: 5
Following is my xml file . I have to get Fields mentioned for each page and for each Type in comma separated string. Please help in how to proceed using Linq
Example : If I want "Type = customFields" defined for "page1" , have to get output in comma separated ProjectID,EmployeeID,EmployeeName,hasExpiration etc
<Pages>
<Page Name="Page1" >
<Type TypeID="customfields">
<Field>ProjectID</Field>
<Field>EmployeeID</Field>
<Field>EmployeeName</Field>
<Field>HasExpiration</Field>
<Field>EndDate</Field>
</Type>
<Type TypeID="Directfields">
<Field>ProjectID</Field>
<Field>EmployeeID</Field>
<Field>EmployeeName</Field>
<Field>HasExpiration</Field>
<Field>EndDate</Field>
<Field>IsInUpdateMode</Field>
<Field>TimesheetSpendLimit</Field>
</Type>
</Page>
<Page Name="Page2" >
<Type TypeID="customfields">
<Field>ProjectID</Field>
<Field>EmployeeID</Field>
<Field>EmployeeName</Field>
<Field>HasExpiration</Field>
<Field>EndDate</Field>
<Field>IsInUpdateMode</Field>
<Field>TimesheetSpendLimit</Field>
</Type>
<Type TypeID="Directfields">
<Field>ProjectID</Field>
<Field>EmployeeID</Field>
<Field>EmployeeName</Field>
<Field>HasExpiration</Field>
<Field>EndDate</Field>
<Field>IsInUpdateMode</Field>
<Field>TimesheetSpendLimit</Field>
</Type>
</Page>
</Pages>
Upvotes: 0
Views: 313
Reputation: 62488
You can do it like this:
var Result = from a in element.Descendants("Page")
from b in a.Descendants("Type")
select new
{
Page = a.Attribute("Name").Value,
Type = b.Attribute("TypeID").Value,
Fields = String.Join(",", b.Elements("Field").Select(x => x.Value))
};
foreach (var item in Result)
{
Console.WriteLine(String.Format("Page = {0}:Type={1}:Fields:{2}", item.Page, item.Type, item.Fields));
}
Check my this blog article as well for more.
Upvotes: 3