Dataset -gt; XML Document - Load DataSet into an XML Document - C#.Net(数据集-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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:数据集->XML 文档 - 将数据集加载到 XML 文档中 - C#.Net


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01