使用Linq查询记录的Xml文件

时间:2014-10-17 09:53:45

标签: c# xml linq

以下是我的xml文件。我必须为每个页面提供字段,并为逗号分隔字符串中的每个类型提供字段。请帮助您了解如何使用Linq

示例:如果我想要" Type = customFields"定义为" page1" ,必须以逗号分隔输出 ProjectID,EmployeeID,EmployeeName,hasExpiration等

<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 个答案:

答案 0 :(得分:3)

你可以这样做:

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

查看我的 this blog article以获取更多信息。