2

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);
            }
        }
    }
Kenmeister
  • 504
  • 2
  • 9
  • 9
  • System.Xml.XmlException: An error occurred while parsing EntityName. Line 12, position 30. I should mention that I have limited control over the source XML(users can add in ampersands without validation). Should I try to work with the response before I try to Deserialize? Thanks, Ken. – Kenmeister Nov 16 '09 at 20:07

4 Answers4

3

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

"Lord &amp; Hogan"

Randolpho
  • 55,384
  • 17
  • 145
  • 179
3

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

empi
  • 15,755
  • 8
  • 62
  • 78
3

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:

Community
  • 1
  • 1
Philip Wallace
  • 7,905
  • 3
  • 28
  • 40
2

Here is function that can be used to replace all of the disallowed chars: https://msdn.microsoft.com/en-us/library/system.security.securityelement.escape(v=vs.110).aspx

Olumide Oyetoke
  • 329
  • 4
  • 17
unclepaul84
  • 1,404
  • 8
  • 15