[C#][ASP.NET]使用XML檔案或XML字串做為DataGridView來源

  • 22482
  • 0
  • 2009-06-11

如何使用XML檔案或XML字串做為DataGridView來源

在藍色小舖中,有網友提出關於使用XML檔案或XML字串做為DataGridView來源的問題,以下分述之

1. XML檔案是否可以像ACCESS一樣作為資料來源直接寫入DataGridView ?
這問題只要透過DataSet.ReadXml方法即可達成

WinForm C# Code

            System.Data.DataSet AuthorsDataSet = new System.Data.DataSet();
            AuthorsDataSet.ReadXml("XMLFile.xml");
            DataGridView1.DataSource = AuthorsDataSet;
            DataGridView1.DataMember = "authors";

ASP.NET (VB) Code

        Dim AuthorsDataSet As New System.Data.DataSet()
        AuthorsDataSet.ReadXml(Server.MapPath("XMLFIle.xml"))
        GridView1.DataSource = AuthorsDataSet
        GridView1.DataBind()

 

執行結果

  

2. 假如使用XML字串是否也可以作為 DataGridView 的資料來源 ?

透過StringReader的方式讀入 XML 字串,之後再透過DataSet.ReadXml方式即可達成。

WinForm C# Code 

            string xmlString =
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
                "<employees xmlns=\"http://schemas.microsoft.com/vsto/samples\">" +
                    "<employee>" +
                        "<name>Karina Leal</name>" +
                        "<hireDate>1999-04-01</hireDate>" +
                        "<title>Manager</title>" +
                    "</employee>" +
                "</employees>";


            System.IO.StringReader reader = new System.IO.StringReader(xmlString);
            System.Data.DataSet AuthorsDataSet = new System.Data.DataSet();
            AuthorsDataSet.ReadXml(reader);
            DataGridView1.DataSource = AuthorsDataSet;
            DataGridView1.DataMember = "employee";
 

 

ASP.NET (VB) Code

        Dim xmlString As String = _
            "<?xml version=""1.0"" encoding=""utf-8"" ?>" & _
                "<employees xmlns=""http://schemas.microsoft.com/vsto/samples"">" & _
                    "<employee>" & _
                        "<name>Karina Leal</name>" & _
                        "<hireDate>1999-04-01</hireDate>" & _
                        "<title>Manager</title>" & _
                    "</employee>" & _
                "</employees>"

        Dim reader As System.IO.StringReader = New System.IO.StringReader(xmlString)
        Dim AuthorsDataSet As New System.Data.DataSet()
        AuthorsDataSet.ReadXml(reader)
        GridView1.DataSource = AuthorsDataSet
        GridView1.DataBind()

 

執行結果

參考
http://www.blueshop.com.tw/board/show.asp?subcde=BRD200904021232506BA&fumcde=
http://msdn.microsoft.com/zh-tw/library/ekw4dh3f(VS.80).aspx