且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

数据集 - > XML文档 - 将DataSet加载到XML文档中 - C#.Net

更新时间:2022-10-22 07:43:04

原始代码:




  • 您不需要调用写入开始和结束的文档方法: DataSet.WriteXmlSchema 生成一个完整的,格式正确的xsd。

  • 在编写模式之后,流位于其结尾,所以当您调用时, XmlReader 将无法读取 XmlDocument.Load



所以主要的是你需要重置使用 Seek MemoryStream 的位置。您也可以简化整个方法:您不需要 XmlReader 或作者。以下内容适用于我:

  XmlDocument xd = new XmlDocument(); 
使用(MemoryStream ms = new MemoryStream())
{
dsContract.WriteXmlSchema(ms);

//将位置重置为流的开头
ms.Seek(0,SeekOrigin.Begin);
xd.Load(ms);
}


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".

Any ideas?

Update

When i do xmlR.ReadInnerXML() it is empty. Does anyone know why?

NLV

A few things about the original code:

  • 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 call XmlDocument.Load.

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