将SQL读取到DataSet到XmlDocument

时间:2012-08-08 22:12:13

标签: c# xml dataset

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

  1. 通过将变量用作参数来填充fill变量是不是很丑(旧的C风格)?
  2. 代码是否可以更紧凑而不是通过String
  3. 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);
    

2 个答案:

答案 0 :(得分:4)

我不知道如何更多地使用C#ish或compact,但是你需要关闭你的Adapter和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);

答案 1 :(得分:1)

尽管Holger的答案非常好,但我实际上是在使用Linq来处理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;