将 SQL 读取到数据集到 XmlDocument

本文关键字:数据集 XmlDocument 读取 SQL | 更新日期: 2024-11-08 11:52:35

下面的代码工作得梦幻。但是它可以变得更紧凑和 C#'ish 吗?特别是我对两个问题有怀疑。

    通过将变量
  1. 用作参数来填充变量不是很丑陋(旧的 C 样式)fill吗?
  2. 代码可以做得更紧凑而不是经过String吗?

C#

String
  connectionString = "...",
  sqlStatement = "select * from Test",
  output = "";
SqlDataAdapter adapter = new SqlDataAdapter(sqlStatement, connectionString);
DataSet dataSet = new DataSet("Contents");
adapter.Fill(dataSet, "Test");
StringWriter stringWriter=new StringWriter();
dataSet.WriteXml(new XmlTextWriter(stringWriter));
XmlDocument document = new XmlDocument();
output = stringWriter.ToString();
document.LoadXml(output);

将 SQL 读取到数据集到 XmlDocument

我不知道

如何使它更C#ish或紧凑,但你确实需要关闭你的适配器和StringWriter。我会使用using块。

   String
       connectionString = "...",
       sqlStatement = "select * from Test",
       output = "";
    DataSet dataSet = new DataSet("Contents");
    using (SqlDataAdapter adapter = new SqlDataAdapter(sqlStatement, connectionString)){
        adapter.Fill(dataSet, "Test");}
    using (StringWriter stringWriter = new StringWriter()) { 
      dataSet.WriteXml(new XmlTextWriter(stringWriter));
      output = stringWriter.ToString();
    };
    XmlDocument document = new XmlDocument();
    document.LoadXml(output);

虽然Holger的回答非常好,但我实际上是在用Linq到XML。我认为,我从他的代码中利用到Linq中的东西更加优雅,如果你的输出是XElement而不是XmlDocument或XmlNode。您也不需要强制转换为 XmlTextWriter。

String
   strConnection = "...",
   strSQL = "select * from Test",
XElement objOutput = null;
DataSet objDataSet = new DataSet("output");
using (SqlDataAdapter objAdapter = new SqlDataAdapter(strSQL, strConnection)){
    objAdapter.Fill(objDataSet, "row");}
using (StringWriter objWriter = new StringWriter()) { 
  objDataSet.WriteXml(objWriter);
  XDocument objDoc = XDocument.Parse(objDataSet.GetXml());
  objOutput = objDoc.Root;
};
return objOutput;