Deserialize XML with ampersand using XmlSerializer()

13,413

Solution 1

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:

Solution 2

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

"Lord & Hogan"

Solution 3

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

Solution 4

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

Share:
13,413
Kenmeister
Author by

Kenmeister

Updated on June 05, 2022

Comments

  • Kenmeister
    Kenmeister almost 2 years

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