I am trying to use LINQ to pop开发者_Python百科ulate a GridView. My XML looks like this:
<?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>
I'm using the following code:
IEnumerable<XElement> matches = from Doctor in doc.Descendants("Doctor") where (int)Doctor.Attribute("ID") > 1 select Doctor;
GridView1.DataSource= matches;
GridView1.DataBind();
This returns an error that the column "specialist" is not found. I want to display the specialist, id attribute and all of the inner elements. My gridview is like so:
<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>
I also made sure that matches
return a value.
Try
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();
You won't be able to use your xml as is - the GridView requires that everything be organized as attributes. The proper schema would be like so:
<DoctorList>
<Doctor ID="1" Specialist="Dentist" UserName="Ahmed" Password="12345" />
<Doctor ID="2" Specialist="oculist" Username="Aya" Password="12345" />
<Doctor ID="3" Specialist="surgery" Username="malak" Password="12345" />
</DoctorList>
I would follow these steps to solve your problem:
Take the above sample xml block and get that to work with your GridView.
Transform your incoming Xml to match that schema, if you don't have control over how it's generated in the first place. There are a number of articles from Google on how to do that...here is one.
Good luck.
精彩评论