Thursday, May 28, 2009

Adding the XML Declaration when calling DataSet.WriteXml(Stream stream) method

using (DataSet ds = new DataSet())

{

//TODO: fill the ds with appropriate data

XmlTextWriter stream = new

XmlTextWriter(@"C:/xmltest.xml", Encoding.UTF8);

ds.WriteXml(stream);

stream.Close();

}



The above example attempts to write the content of the DataSet to an xml file using the DataSet.WriteXml method. The xml file doesn't contain the XML declaration.

Content of xml file:

<NewDataSet />



TIP: To include the XML declaration in the output file, call the method WriteStartDocument() on the stream object prior to the WriteXml() method call.

using (DataSet ds = new DataSet())

{

//TODO: fill the ds with appropriate data

XmlTextWriter stream = new

XmlTextWriter(@"C:/xmltest.xml", Encoding.UTF8);

stream.WriteStartDocument();

ds.WriteXml(stream);

stream.Close();

}



Content of xml file:

<?xml version="1.0" encoding="utf-8"?>

<NewDataSet />

2 comments:

Anonymous said...

Very good tip, thank you!!!

Anonymous said...

Thanks!
Very Useful for me.