0

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>
1

1 Answer 1

3

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));
}

WORKING FIDDLE

Check my this blog article as well for more.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.