Root element is missing in InfoPath when loading a MemoryStream in an XPathDocument
Learn how you can solve the 'Root element is missing' error if you're trying to load a MemoryStream into an XPathDocument in InfoPath.
While I have written about this topic before, back then, the error in question, Root element is missing, took place on an InputStream of a Request object.
This time however, while writing an article about copying the contents of a SharePoint list to a repeating table in InfoPath using XSLT and C#, I tried to load a MemoryStream object in an XPathDocument object and got the Root element is missing error.
I always prefer to use an XPathDocument object instead of an XmlDocument object whenever I do not have to modify the XML data in the object. The XPathDocument class "provides a fast, read-only, in-memory representation of an XML document using the XPath data model", which makes it ideal for reading XML data that does not need to be modified. If you want to modify XML however, you can use the XmlDocument class instead.
The first step in troubleshooting the Root element is missing error is to make sure that whatever XML is contained in the MemoryStream that you want to load into the XPathDocument object is well-formed. You can do this by writing the MemoryStream contents out to a file on disk using
System.IO.File.WriteAllBytes(@"C:\memorystream.xml", ms.GetBuffer());
where ms is a MemoryStream, and then check the XML outputted to the file. The resulting XML document should have one top-level element, i.e., the root element.
If the XML data contained in the MemoryStream has a root element and is well-formed, the next step is to check the current position in the stream. If this is not zero, set it to zero using
ms.Position = 0;
where ms is a MemoryStream.
The second step solved my Root element is missing error. The position in the MemoryStream was 577 and not 0, which caused the XPathDocument to return the Root element is missing error, because it could not find a root element at position 577.
Related Posts
Copyright: This article may not be used on web sites (whether personal or otherwise), copied, disseminated, altered, printed, published, broadcasted, or reproduced in any way without an expressed written consent of S.Y.M. Wong-A-Ton. Usage of techniques demonstrated in this article may be used within any Microsoft InfoPath project. This article is provided without any warranties. Copyright for this article is non-transferrable and remains with the author, S.Y.M. Wong-A-Ton.


