2

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

  1. fill通过将变量用作参数来填充变量不是很丑陋(旧的 C 风格)吗?
  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);
4

2 回答 2

4

我不知道如何使它更 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);
于 2012-08-08T23:44:58.230 回答
1

虽然 Holger 的回答非常好,但我实际上是在使用 Linq to XML。我认为,如果您的输出是 XElement 而不是 XmlDocument 或 XmlNode,我从他的代码到 Linq 中利用的内容更加优雅。您也不需要强制转换为 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;
于 2013-04-09T11:47:10.650 回答