shakz
shakz

Reputation: 639

Invalid at the top level of the document error when reading XML file

I am getting error like this. The XML page cannot be displayed Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later. In the button click i wrote this.

String strUrl = "https://secure.dev.gateway.gov.uk/submission";    
HttpWebRequest req  = ( HttpWebRequest )WebRequest.Create( strUrl );
req.ContentType     = "text/xml";
req.Method          = "POST";
req.Accept          = "text/xml";
req.PreAuthenticate = true;
req.Credentials     = new NetworkCredential("189", "");
req.UseDefaultCredentials = true;

System.IO.Stream stream = req.GetRequestStream();
string strXML = GetXmlString("C:\\Documents and Settings\\com\\My Documents\\Downloads\\18march\\VatDecRequest_ValidSample v1.0.xml");
byte[] arrBytes = System.Text.ASCIIEncoding.ASCII.GetBytes( strXML );
stream.Write( arrBytes, 0, arrBytes.Length );
stream.Close();
WebResponse resp = req.GetResponse();
Stream respStream = resp.GetResponseStream();
StreamReader rdr = new StreamReader( respStream, System.Text.Encoding.ASCII );
Response.ContentType = "text/xml";
string strResponse = rdr.ReadToEnd();
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(strResponse);
xmldoc.Save("C:\\test9.xml");

Upvotes: 0

Views: 3327

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500365

Why are you loading the file as a string and then encoding it in ASCII? Why not just load the binary data and serve that directly? (File.ReadAllBytes is probably your friend.)

I suspect that the XML file is actually in UTF-8, quite possibly with a byte-order mark which can't be represented in ASCII.

The same goes for both the request and the response - where feasible just get the XML parser to deal with a binary stream and figure out the encoding for itself.

Upvotes: 2

Related Questions