问题
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 & Hogan"
回答3:
&
in xml should be replaced with &
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