Deserialize XML with ampersand using XmlSerializer()

故事扮演 提交于 2019-12-22 15:26:07

问题


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

回答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:

  • How do I escape ampersands in XML
  • Why can’t RSS handle the Ampersand?
  • parsing XML with ampersand
  • Deserialize XML with ampersand using XmlSerializer()
  • there are more!



回答2:


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

"Lord &amp; Hogan"




回答3:


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




回答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



来源:https://stackoverflow.com/questions/1744046/deserialize-xml-with-ampersand-using-xmlserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!