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

Dan Cope picture Dan Cope · Nov 22, 2013 · Viewed 18.5k times · Source

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); 

Answer

Dan Cope picture Dan Cope · Nov 23, 2013

I managed to resolve this. Instead of passing a string with all the xml in it and using Server.UrlEncode I used the XmlWriter class and StringBuilder. All your replies were helpful and much appriciated, I would up vote them but I cannot do that feature yet. Maybe this will help others in the future. Thanks

        XmlWriter writer;
        StringBuilder sb = new StringBuilder();
        writer = XmlWriter.Create(sb);
        writer.WriteStartElement("serv_request");
        writer.WriteStartElement("head");
        writer.WriteStartElement("securityContext");
        writer.WriteStartElement("account");
        writer.WriteString("MyAccountName");
        writer.WriteEndElement();
        writer.WriteStartElement("key");
        writer.WriteString("MyKey");
        writer.WriteEndElement(); //closes Key Element
        writer.WriteEndElement(); // closes securityContent
        writer.WriteEndElement(); //closes head
        writer.WriteStartElement("body");
        writer.WriteStartElement("username");
        writer.WriteString("MyUserName");
        writer.WriteEndElement(); // closes username
        writer.WriteEndElement(); //closes body
        writer.WriteEndElement(); //closes serv_request
        writer.Close();

        NameValueCollection nvc = new NameValueCollection();           
        nvc.Add("xml", sb.ToString());          

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

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