The code below works dreamy. But can it be made more compact and C#'ish? Especially i have suspicions regarding two issues.
- Isn't it ugly (old C-style) filling
fill
a variable by using it as a in-parameter? - Can the code be made more compact instead of going through a
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);
Although Holger's answer is really good, I was actually working with Linq to XML. What I leveraged from his code into Linq is even more elegant, I think, if your output is an XElement instead of an XmlDocument or an XmlNode. You also don't need to cast to XmlTextWriter.
I don't know about making it more C#ish or compact, but you do need to close your Adapter and StringWriter. I would use the
using
block.