Lost XML file declaration using DataSet.WriteXml (Stream)

I had a dataset with some data. When I tried to write this DataSet to a file everything was fine. But when I tried to write it to a MemoryStream, the XML file expression was lost. The code looks like this:

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 the testFile.xml file I got:

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

      

But when I open the stream with StreamReader I only get:

//balabala

      

Someone said that I can manually insert the XML file declaration into my stream. It works, but it seems so ugly. Do you know why he gave up the first line and easier solution?

0


source to share


3 answers


It has not been dropped. Just not included. Although it is highly recommended that 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 XmlWriter.WriteStartDocument to embed the xml declaration into the stream like this:

MemoryStream stream = new MemoryStream();
var writer = XmlWriter.Create(stream);
writer.WriteStartDocument(true);
dSet.WriteXML(stream);

      

+3


source


I am trying to follow your solution with a DataTable and is not working 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);
    }
}

      

0


source


If you break down the 2.0 code, you can see that the method WriteXml

that takes the filename explicitly writes the declaration ( XmlWriter.WriteStartDocument

), but the methods WriteXml

that take in the stream or writer don't.

0


source







All Articles