填充LINQ to XML to Gridview

时间:2011-09-14 14:07:09

标签: asp.net c#-3.0

我正在尝试使用LINQ来填充GridView。我的XML看起来像这样:

      <?xml version="1.0" ?> 
- <!-- Created @ 9/14/2011 1:16:52 PM
  --> 
- <DoctorList>
- <Doctor ID="1" Specialist="Dentist">
  <Username>Ahmed</Username> 
  <Password>12345</Password> 
  </Doctor>
- <Doctor ID="2" Specialist="oculist">
  <Username>Aya</Username> 
  <Password>12345</Password> 
  </Doctor>
- <Doctor ID="3" Specialist="surgery">
  <Username>malak</Username> 
  <Password>12345</Password> 
  </Doctor>
  </DoctorList>

我正在使用以下代码:

IEnumerable<XElement> matches = from Doctor in doc.Descendants("Doctor") where (int)Doctor.Attribute("ID") > 1 select Doctor;
GridView1.DataSource= matches;
       GridView1.DataBind();

这将返回未找到“专家”列的错误。我想显示expert,id属性和所有内部元素。我的gridview是这样的:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  
            CellPadding="4" HeaderStyle-BackColor="blue" HeaderStyle-ForeColor="White" 
            HeaderStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="True" 
            ondatabound="GridView1_DataBound">
            <Columns>  
            <asp:BoundField HeaderText="Specialist" DataField="Specialist" /> 
            <asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-HorizontalAlign="Right" />
            <asp:BoundField HeaderText="Username" DataField="Username" ItemStyle-HorizontalAlign="Right" />
            <asp:BoundField HeaderText="Password" DataField="Password" ItemStyle-HorizontalAlign="Right" />
             </Columns>

<HeaderStyle HorizontalAlign="Center" BackColor="Blue" Font-Bold="True" ForeColor="White"></HeaderStyle>
           </asp:GridView>

我还确保matches返回一个值。

2 个答案:

答案 0 :(得分:3)

尝试

IEnumerable<XElement> matches = 
               from Doctor in doc.Descendants("Doctor") 
               where (int)Doctor.Attribute("ID") > 1 
               select new {
                              Specialist = Doctor.Attribute("Specialist").Value,
                              ID = Doctor.Attribute("ID").Value,
                              Username = Doctor.Element("Username").Value,
                              Password = Doctor.Element("Password").Value
                };

GridView1.DataSource = matches;
GridView1.DataBind();

答案 1 :(得分:0)