Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

c# - Query Xml File for Records using Linq

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...