如何将xml绑定到gridview

时间:2011-07-26 01:26:33

标签: c# asp.net xml bind

这是我的xml文件

<ISPChecklist>
            <Domain name="Coping Skills">
            <Indicator>
                Client shows impovement in either 1 of the areas listed below and shows reduction in frequency of inapporiate coping behaviors :
                - anger management
                - ability to make concrete plans about his/her future
                - self percetion/self worth
                - expand internal locus of control.
            </Indicator>
            <AttainmentDate></AttainmentDate>
            <Remarks></Remarks>
        </Domain>
</ISPChecklist>

这是我的网格视图

<asp:GridView ID="ISPChecklist" runat="server" 
                OnRowDataBound="OnDataBound" 
                onselectedindexchanged="ISPChecklist_SelectedIndexChanged">
            <Columns>
            <asp:BoundField HeaderText="Domain" DataField= "Domain" />
            <asp:BoundField HeaderText="Indicator" DataField="Indicator" />
            <asp:TemplateField HeaderText="Date Of Attainment">
                <ItemTemplate>
                    <asp:TextBox runat="server" ID="TB_Date" Columns="5"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Remarks">
                <ItemTemplate>
                    <asp:TextBox runat="server" ID="TB_Remarks" Columns="5"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            </Columns>
            </asp:GridView>

这是我的.cs文件

DataSet checklistDataSet;

string filePath = Server.MapPath("clientISPChecklist.xml");
        checklistDataSet = new DataSet();
        //Read the contents of the XML file into the DataSet

        checklistDataSet.ReadXml(filePath);
        ISPChecklist.DataSource = checklistDataSet.Tables[0].DefaultView;
        ISPChecklist.DataBind();//errors occurs here

每当我运行这组代码时,我都会收到一条错误消息,指出“在所选数据源上找不到名为'Coping Skills'的字段或属性”。 anyoen知道如何解决它吗?如果没有,有任何教程或指南可用

2 个答案:

答案 0 :(得分:1)

使用XMLDataSourceXPath()方法。

答案 1 :(得分:0)

我想Linq-XML是更好的选择。

XDocument doc = XDocument.Load(MapPath("~/filename.xml"));

var result = from n in doc.Descendants("Domain")
             select new
                {
                   Domain = n.HasAttributes ? n.Attribute("name").Value : "",
                   Indicator=n.Element("Indicator").Value,
                   AttainmentDate = n.Element("AttainmentDate").Value,
                   Remark=n.Element("AttainmentDate").Value 
               };

ISPChecklist.DataSource = result.ToList();
ISPChecklist.DataBind();