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?
source to share
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);
source to share
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);
}
}