本文介绍了使用DataSet.WriteXml(Stream)丢失XML文件声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,其中包含一些数据。当我试图将这个DataSet写入文件时,一切都OK。但是当我尝试将其写入MemoryStream时,XML文件声明丢失。
代码如下:

  DataSet dSet = new DataSet(); 
//加载模式,填充数据
dSet.WriteXML(testFile.xml);
MemoryStream stream = new MemoryStream();
dSet.WriteXML(stream);
stream.Seek(0,SeekOrigin.Begin);

当我打开文件testFile.xml时,我得到:

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

但是当我使用StreamReader打开流时,我只得到: / p>

  // balabala 


$ b有人说我可以手动在我的流中插入XML文件声明。它的作品似乎很丑陋。你知道为什么它放弃第一行和任何更简单的解决方案?

解决方案

没有被删除。不包括在内。虽然强烈建议xml声明不是xml规范的必需元素。





您可以使用XmlWriter.WriteStartDocument在流中包含xml声明,如下所示:

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


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?

解决方案

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

这篇关于使用DataSet.WriteXml(Stream)丢失XML文件声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:26