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.WriteXmlSchemaproduces a complete, well-formed xsd. - After writing the schema, the stream is positioned at its end, so there's nothing for the
XmlReaderto 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
基础教程推荐
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 如果条件可以为空 2022-01-01
- 将数据集转换为列表 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
