Got a bit of strangeness going on when assigning an XML stream to an XmlTextReader. It's actually a MemoryStream representing a well-formed ASCII XML document (I've confirmed this). The following code snippet works...
XmlTextReader tr = new XmlTextReader(stream);
stream.Position = 0; // this is the key to making it work
tr.Read();
... and the next code snippet throws the error "root element is missing"...
XmlTextReader tr = new XmlTextReader(stream);
//stream.Position = 0;
tr.Read();
If I save the stream to a file, then initialize the XmlTextReader object with the filename everything works fine. I am actually using the XmlTextReader object to validate the Xml against an XSD. Here's the complete code that I'm using...
XmlTextReader tr = new XmlTextReader(stream);
XmlValidatingReader reader = new XmlValidatingReader(tr);
reader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
reader.ValidationType = ValidationType.Schema;
stream.Position = 0; // this MUST be set to 0
XmlDocument x = new XmlDocument();
x.Load(reader); // if stream.Position isn't explicitly set to 0 I get the "root element
// is missing" error on this call
It's strange that I can set stream.Position = 0 anywhere before the x.Load() call, but it DOES have to be set (or I get the error stated above). The following code works without problem...
XmlValidatingReader reader = new XmlValidatingReader(stream,
System.Xml.XmlNodeType.Element, null);
reader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
reader.ValidationType = ValidationType.Schema;
XmlDocument x = new XmlDocument();
x.Load(reader);
If the XmlTextReader is taken out and the stream is passed directly into the XmlValidatingReader everything works as you would think it should. I know this was fairly lengthy but hopefully easy to follow. Anyone out there have any idea why this may be happening???
My thoughts...
As stated in code snippet #3, it doesn't matter where stream.Position=0 is set, just as long as it's set before the x.Load() call. Maybe the XmlTextReader object doesn't initialize the stream to the first position when loaded and since the stream is referenced by address in .Net in all sub-objects, where stream.Position is set doesn't matter? The XmlValidatingReader, though, does seem to initilize the stream correctly. Any thoughts?
GraemeBryce - 13 Jul 2004 16:31 GMT
I have a very similar issue. It is of note that the error can only b
replicated on Windows Server 2004 and not on earlier server O
version.
It is indeed odd
Many thanks for the fix.
Graeme
> *Got a bit of strangeness going on when assigning an XML stream to a
> XmlTextReader. It's actually a MemoryStream representing
[quoted text clipped - 56 lines]
> is set doesn't matter? The XmlValidatingReader, though, does seem t
> initilize the stream correctly. Any thoughts?
-
GraemeBryc