tags:

views:

375

answers:

3

Hello

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

+2  A: 

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);
}
Jeff Sternal
I want the schema of the dataset in a separate XML document.
NLV
A: 

All you really need to do is to call contractHistoryXMLSchemaDoc.Save(ms). That will put the xml into the MemoryStream.

XmlDocument contractHistoryXMLSchemaDoc = new XmlDocument();

using (MemoryStream ms = new MemoryStream())
{
    contractHistoryXMLSchemaDoc.Save(ms);
    ms.Flush();
}
gbogumil
I think my title for the question has confused you. I've the dataset. I want to load it into an xml document.
NLV
+1  A: 
XmlDocument contractHistoryXMLSchemaDoc = new XmlDocument();

using (MemoryStream ms = new MemoryStream())
{
   dsContract.WriteXml(ms);
   ms.Seek(0, SeekOrigin.Begin);
   using(XmlReader xmlR = XmlReader.Create(ms))
   {
       contractHistoryXMLSchemaDoc.Load(xmlR);
   }

}
JohnForDummies