views:

302

answers:

4

The following code breaks when the XML has data like "Lord & Hogan". Any suggestions? Thanks, Ken

    private T GetResponse<T>(String apiObject, String query)
    {
        //Deserialize XML into the type specified.
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BuildRequestUri(apiObject, query));
        using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
        {
            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(T));
                return (T)ser.Deserialize(resp.GetResponseStream());
            }
            catch (Exception e)
            {
                error = e.InnerException.ToString();
                return default(T);
            }
        }
    }
+3  A: 

you should XML-encode data like "Lord & Hogan". It should be encoded like this:

"Lord &amp; Hogan"

Randolpho
+2  A: 

& in xml should be replaced with &amp; otherwise it's invalid character.

empi
+3  A: 

From here:

A literal ampersand inside an XML tag is not allowed by the XML standard, and such a document will fail to parse by any XML parser.

Other similar questions on StackOverflow:

Philip Wallace
A: 

Here is function that can be used to replace all of the disallowed chars: http://msdn.microsoft.com/en-us/library/system.security.securityelement.escape(VS.80).aspx

unclepaul84
Kenmeister