Lost XML file declaration using DataSet.WriteXml(Stream)

放肆的年华 提交于 2019-12-11 18:05:23

问题


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?


回答1:


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 XmlWriter.WriteStartDocument to include the xml declaration in the stream like so:

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



回答2:


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);
    }
}



回答3:


If you disassemble the 2.0 code you'll see that the WriteXml method that takes a file name explictly writes out the declaration (XmlWriter.WriteStartDocument) but the WriteXml methods that take a stream or writer do not.



来源:https://stackoverflow.com/questions/392626/lost-xml-file-declaration-using-dataset-writexmlstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!