本文介绍了数据集->XML 文档 - 将数据集加载到 XML 文档中 - C#.Net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试以 xml 格式读取数据集并将其加载到 XML 文档中.
I'm trying to read a dataset as xml and load it into an XML Document.
XmlDocument contractHistoryXMLSchemaDoc = new XmlDocument();
using (MemoryStream ms = new MemoryStream())
{
//XmlWriterSettings xmlWSettings = new XmlWriterSettings();
//xmlWSettings.ConformanceLevel = ConformanceLevel.Auto;
using (XmlWriter xmlW = XmlWriter.Create(ms))
{
xmlW.WriteStartDocument();
dsContract.WriteXmlSchema(xmlW);
xmlW.WriteEndDocument();
xmlW.Close();
using (XmlReader xmlR = XmlReader.Create(ms))
{
contractHistoryXMLSchemaDoc.Load(xmlR);
}
}
}
但我收到错误消息 - 缺少根元素".
But I'm getting the error - "Root Element Missing".
有什么想法吗?
更新
当我执行 xmlR.ReadInnerXML() 时,它是空的.有谁知道为什么?
When i do xmlR.ReadInnerXML() it is empty. Does anyone know why?
NLV
推荐答案
关于原代码的几点说明:
A few things about the original code:
- 您不需要调用写入开始和结束文档方法:
DataSet.WriteXmlSchema
生成完整、格式良好的 xsd. - 写入架构后,流位于其末尾,因此当您调用
XmlDocument.Load
时,XmlReader
没有任何内容可供读取.
- You don't need to call the write start and end document methods:
DataSet.WriteXmlSchema
produces a complete, well-formed xsd. - After writing the schema, the stream is positioned at its end, so there's nothing for the
XmlReader
to read when you callXmlDocument.Load
.
所以主要是你需要使用Seek
重置MemoryStream
的位置.您还可以稍微简化整个方法:您不需要 XmlReader
或 writer.以下对我有用:
So the main thing is that you need to reset the position of the MemoryStream
using Seek
. You can also simplify the whole method quite a bit: you don't need the XmlReader
or writer. The following works for me:
XmlDocument xd = new XmlDocument();
using(MemoryStream ms = new MemoryStream())
{
dsContract.WriteXmlSchema(ms);
// Reset the position to the start of the stream
ms.Seek(0, SeekOrigin.Begin);
xd.Load(ms);
}
这篇关于数据集->XML 文档 - 将数据集加载到 XML 文档中 - C#.Net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!