tags:

views:

882

answers:

2

I had a Dataset with some data in it. When I tried to write this DataSet into a file, everything was OK. But When I tried to write it into a MemoryStream, the XML file declaration was lost. The code looks like:

DataSet dSet = new DataSet();
//load schema, fill data in
dSet.WriteXML("testFile.xml");
MemoryStream stream = new MemoryStream();
dSet.WriteXML(stream);
stream.Seek(0,SeekOrigin.Begin);

When I opened file testFile.xml, I got:

<?xml version="1.0" standalone="yes"?>
//balabala

But When I open the stream with StreamReader, I only got:

//balabala

Somebody said I can insert XML file declaration in my stream manually. It works but seems so ugly. Do you know why it dropped the first line and any more simple solution?

A: 

It wasn't dropped. Simply not included. Though it is highly recommend the xml declaration is not a required element of the xml specification.

http://msdn.microsoft.com/en-us/library/ms256048(VS.85).aspx

You can use XmlTextWriter.WriteStartDocument to include the xml declaration in the stream like so:

MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
writer.WriteStartDocument();
dSet.WriteXML(stream);
codeelegance
-1 for using `XmlTextWriter`, which has been deprecated since .NET 2.0.
John Saunders
A: 

I try your solution with DataTable and don't work correctly.

using (MemoryStream stream = new MemoryStream()) {
    using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8)) {
        writer.WriteStartDocument(); //<?xml version="1.0" encoding="utf-8"?>
        writer.WriteRaw("\r\n"); //endline
        writer.Flush(); //Write immediately the stream
        dTable.WriteXml(stream);
    }
}
What does it do wrong? BTW, use `XmlWriter.Create` instead of `new xmlTextWriter()`. `XmlTextWriter` has been deprecated since .NET 2.0.
John Saunders
If you run that code with DataTable, first it writes the table, and then the declaration. Thanks for the suggestion. I'll try to use XmlWriter.Create.