How to determine if a string value is in XML format?

Asked

Viewed 115 times

2

I am connecting with an API, or service as you wish, which returns an xml when it finds data in the database, but unfortunately it returns a string if nothing is found or an error occurs. In my application I am using the following code to connect to this API and recover the data:

 WebRequest request = WebRequest.Create(_fileUrl);

 HttpWebResponse response = (HttpWebResponse) request.GetResponse();

 Stream dataStream = response.GetResponseStream();

 var reader = new StreamReader(dataStream);

 string responseFromServer = reader.ReadToEnd();

 xmlDoc.LoadXml(responseFromServer);

As expected when there is no data in the database an error occurs when loading xmlDoc because the responseFromServer variable is not XML but a string.

The question is: How do I identify whether my string returned an xml or not? I don’t want to ""try" to load and if it doesn’t work out that what came was a string. I may be masking other errors while doing so.

1 answer

4


You can check whether response.ContentType corresponds to application/xml or text/xml and use this information to make the decision. If the service is well configured, it should send this header (and send text/plain to the error message).

  • perfect, well better than generating an exception to check the "provenance" of the return. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.