Search code examples
c#xmlnamevaluecollection

XML response error: Invalid at the top level of the document


I am getting an error back and following the API manual I received on how to encode my request. Below is my request..

string url = "[My url to send request to]";

string xmlrequest = "<serv_request><head><securityContext><account>[account]</account><key>[my account key]</key></securityContext></head><body><username>[my user name]</username></body></serv_request>";

NameValueCollection nvc = new NameValueCollection();
nvc.Add("xml", Server.UrlEncode(xmlrequest));


WebClient client = new WebClient();

byte[] byteresponse = client.UploadValues(url, nvc);

string xmlresponse = client.Encoding.GetString(byteresponse);

I am getting a response back with the error. Invalid at the top level of document.

Edit.. Adding the Instructions from the API Manual provided to me..

string url = " http://[domain_name]/_gateway/api/[filename].asp"; 

// formulate the XML request here 

string xmlrequest = "<serv_request>...</serv_request>";  

NameValueCollection nvc = new NameValueCollection(); 
nvc.Add("xml", Server.UrlEncode(xmlrequest)); 

WebClient client = new WebClient(); 
byte[] byteresponse = client.UploadValues(url, nvc); 

string xmlresponse = client.Encoding.GetString(byteresponse); 

Solution

  • It sounds like the server is not responding with a proper xml, it may be returning an empty string or any text that is not a well formed XML.

    Try and capture the xml you are sending and use a tool like soapUI to send the request and see the response it gives to you.

    Also maybe try this in stead of your last line of code:

    string xmlresponse = System.Text.Encoding.UTF8.GetString(byteresponse);