asp.Net:创建一个由XML文件填充的Gridview

时间:2016-08-22 10:05:20

标签: c# asp.net xml gridview

我有以下XML文件:

<?xml version="1.0" standalone="yes"?>
<counter>
  <count>
    <homeHits>9</homeHits>
    <aboutHits>7</aboutHits>
    <galleryHits>6</galleryHits>
    <quoteHits>15</quoteHits>
    <contactHits>4</contactHits>
  </count>
</counter>

我正在创建一个简单的asp:GridView来在.aspx页面上显示所有这些数据:

<asp:Gridview ID="gvDisplayHits" runat="server">

</asp:Gridview>

如何填写此网格视图以此格式显示信息?:

Page     | # Of Hits
--------------------
Home     | 9
About    | 7
Gallery  | 6
Quote    | 15
Contact  | 4

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

请试试这个

        DataSet ds = new DataSet();
        string s = Server.MapPath("test.xml"); // test.xml is your xml file
        ds.ReadXml(s);
        DataTable oldTable = ds.Tables[0];

        DataTable newTable = new DataTable();           

        newTable.Columns.Add("Page");
        for (int i = 0; i < oldTable.Rows.Count; i++)
            newTable.Columns.Add("# Of Hits");

        for (int i = 0; i < oldTable.Columns.Count; i++)
        {
            DataRow newRow = newTable.NewRow();
            newRow[0] = oldTable.Columns[i].Caption.Replace("Hits","");
            for (int j = 0; j < oldTable.Rows.Count; j++)
                newRow[j + 1] = oldTable.Rows[j][i];
            newTable.Rows.Add(newRow);
        }
       // set newTable as datasource to grid view.