从数据中读取数据生成XML性能问题

cmlibo 2012-02-15 05:58:35
今天看到公司从数据库中取出数据生成XML使用的方式为,先读取数据到DataSet,再转换成string,最后再转成XML,如(代码随便写的):

public static XmlDocument ExecuteDataSet(string connectionString, string spName)
{

if (string.IsNullOrEmpty(connectionString))
throw new ArgumentNullException("connectionString");
if (string.IsNullOrEmpty(spName))
throw new ArgumentNullException("spName");
XmlDocument doc = new XmlDocument();

using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = spName;
cmd.Connection = connection;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ds.DataSetName = "Result";
ds.Tables[0].TableName = "CompanyList";
string xml = ds.GetXml();
doc.LoadXml(xml);
connection.Close();
}
return doc;
}


然后我自己用了另外一种方式,用ExecuteXmlReader实现的,如:

public static XmlDocument ExecuteXmlReader(string connectionString, string spName)
{

if (string.IsNullOrEmpty(connectionString))
throw new ArgumentNullException("connectionString");
if (string.IsNullOrEmpty(spName))
throw new ArgumentNullException("spName");
XmlDocument doc = new XmlDocument();

using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = spName;
cmd.Connection = connection;
doc.Load(cmd.ExecuteXmlReader());
connection.Close();
}
return doc;
}


经过测试,发现使用ExecuteXmlReader生成XML的时间要大于等于使用DataSet再转成xml的时间,
尽管如此 我还是想问下 那种方式好些。
PS:使用ExecuteXmlReader方式需在查询语句后加 FOR XML AUTO,root('Result'),elements
第一种方式用的存储过程:
ALTER PROCEDURE [DC].[P_Int_Pub_Company_List]
AS
BEGIN
select snCompID as CompID,vcCompany as Company from Pub_Company order by snOrder asc
END

第二种:
ALTER PROCEDURE [DC].[P_Int_Pub_Company_List_XML]
AS
BEGIN
select snCompID as CompID,vcCompany as Company from Pub_Company as CompanyList order by snOrder asc FOR XML AUTO,root('Result'),elements
END
...全文
53 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
·不羡仙· 2012-02-15
  • 打赏
  • 举报
回复
没有考虑这样的问题,我的思路是这样,可以一起讨论下,普通数据的方式,读取数据库信息到List<object>,针对object重写tostring()方法,返回xml格式的属性信息。

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧