从数据中读取数据生成XML性能问题
今天看到公司从数据库中取出数据生成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]--------------------编程问答-------------------- 没有考虑这样的问题,我的思路是这样,可以一起讨论下,普通数据的方式,读取数据库信息到List<object>,针对object重写tostring()方法,返回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
补充:.NET技术 , C#