使用存储过程 对于 XML 路径直接读入绑定到数据网格视图的数据集?



我有以下存储过程:

CREATE Procedure [dbo].[usp_GetMyAlbumData]  
AS
SELECT * 
FROM [dbo].[tblAlbumDetails]  
FOR XML PATH('AlbumDetail'), ROOT('AlbumDetails'), TYPE

我需要弄清楚如何使用usp_ReportGetMyAlbumData生成的 XML 在数据网格视图中显示数据。

例如,我的数据库中有一条记录。当我在 SQL Server 2012 中运行usp_ReportGetMyAlbumData存储过程时,我得到以下结果:

<AlbumDetails>
<AlbumDetail>
<MusicID>1</MusicID>
<AlbumDesc>Jones</AlbumDesc>
<AlbumDate>2018-10-13T15:55:49.843</AlbumDate>
<AlbumPrice>4.0000</AlbumPrice>
</AlbumDetail>
</AlbumDetails>

我想使用 C# 将此 XML 结果(或usp_ReportGetMyAlbumData生成的任何其他 XML 结果(写入数据集,以便我可以将其绑定到 DataGridView。

我知道如何将 XML 文件写入数据集,但存储过程返回 XML,而不是 XML文件

我需要编写什么代码才能使用存储过程生成的 XML 中的数据填充数据集?

xml 将是数据库中的字符串。 所以我会使用 xml linq parse 方法来将字符串 a 放入数据表中。 然后将数据表设为 DGV 的源。 请参阅下面的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
const string FILENAME = @"c:temptest.xml";
public Form1()
{
InitializeComponent();
//data will be from the database a string
//I'm reading fron a file for testing
string xml = File.ReadAllText(FILENAME);
DataTable dt = new DataTable();
dt.Columns.Add("MusicID", typeof(int));
dt.Columns.Add("AlbumDesc", typeof(string));
dt.Columns.Add("AlbumDate", typeof(DateTime));
dt.Columns.Add("AlbumPrice", typeof(decimal));
XDocument doc = XDocument.Parse(xml);
foreach(XElement album in doc.Descendants("AlbumDetail"))
{
dt.Rows.Add(new object[] {
(int)album.Element("MusicID"),
(string)album.Element("AlbumDesc"),
(DateTime)album.Element("AlbumDate"),
(decimal)album.Element("AlbumPrice")
});
}
dataGridView1.DataSource = dt;
}
}
}
string xml = "your xml here";
var ds = new DataSet();
using (var reader = new StringReader(xml))
{
ds.ReadXml(reader);
}
dataGridView.DataSource = ds.Tables[0];

最新更新