views:

2619

answers:

2

Greetings all.

I'm getting an asp.net error "Root element is missing" when I load the results of a REST request into an XmlDocument. The same REST request looks fine and returns valid results when I execute it using the Firefox addon "RESTTEST". But the error shows up in the C#.net code-behind. Does anyone know what might cause this? Here is the relevant code:

HttpWebResponse response = null;
response = (HttpWebResponse)request.GetResponse();
HttpStatusCode statusCode = response.StatusCode;
Stream responseData = response.GetResponseStream();
StreamReader sr = new StreamReader(responseData);
XmlTextReader reader = new XmlTextReader(sr);
XmlDocument doc = new XmlDocument();
doc.Load(sr); // here is where the error occurs.

My goal is to load the results of the REST request into a traverse-able XML data model which I can then grab elements and their values from.

When I use this code, I get the expected results. What is the difference?

while (reader.Read())
{
  switch (reader.NodeType)
  {
    case XmlNodeType.Element: // The node is an Element.
      Response.Write("Element Name: " + reader.Name);
      while (reader.MoveToNextAttribute()) // Read attributes.
      Response.Write(" " + reader.Name + "='" + reader.Value + "'");
      Response.Write("<br />");
      break;
    case XmlNodeType.Text: //Display the text in each element.
      Response.Write("Element value: " + reader.Value);
      Response.Write("Read key=" + reader.Name + ", value=" + reader.Value + "<br/>");
      break;
    case XmlNodeType.EndElement: //Display end of element.
      Response.Write("<br />");
      break;
    }
  }
A: 

Try using sr.ReadToEnd() to see what's being returned to you. It's probably an empty string.

Also, you should be using XmlReader.Create if you're using .NET 2.0 or above; XmlTextReader is deprecated.

See A REST Client Library for .NET, Part 1 for an example that uses XML Serialization. (sorry, there is no part 2).

John Saunders
+1  A: 

It looks like the XML is a fragment rather than a fully formed XML document-- that's why it didn't have the root. To get this to work you have to configure the XMLDocument object to accept fragments...

NorthK