下面的代码很有效。但它可以变得更紧凑和C#'ish?特别是我怀疑两个问题。
fill
变量是不是很丑(旧的C风格)?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);
答案 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;