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
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
