How can I prevent '&' from being converted to '& amp' when XML serialized in ASP.NET Web API?
I am creating a booking service using ASP.NET Web API,
For which response model is it something like this:
[XmlRoot("RateList")]
public class RateList
{
[XmlElement("Rate")]
public List<Rate> Rate { get; set; }
}
public class Rate
{
[XmlAttribute("Code")]
public string Code { get; set; }
[XmlAttribute("ErrorMessage")]
public string ErrorMessage { get; set; }
[XmlElement("RoomRate")]
public List<RoomRate> RoomRate { get; set; }
}
public class RoomRate
{
[XmlAttribute("URL")]
public string URL { get; set; }
}
The answer must be in XML format, so I serialized below,
return Request.CreateResponse<RateList>(HttpStatusCode.OK, objRateList, Configuration.Formatters.XmlFormatter);
my Global.asax file
WebApiConfig.Register(GlobalConfiguration.Configuration);
var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;
The actual answer should be like this:
<RateList
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Rate Code="174511">
<RoomRate URL="https://somedomain.com/planning/booking?start=2015-06-02&end=2015-06-04&id=174511&adults=2&childAges=0&room=1"/>
</Rate>
</RateList>
But I am currently getting the answer below where "&" is changed to " &
":
<RateList
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Rate Code="174511">
<RoomRate URL="https://somedoamin.com/planning/booking?start=2015-06-02&end=2015-06-04&id=174511&adults=2&childAges=0&room=1"/>
</Rate>
</RateList>
How can I avoid this change in my answer?
Thanks in advance.
source to share
This is the correct behavior. If this cannot be avoided, the XML will be poorly formed (that is, the parser should report an error and not parse it). If you want to generate XML you need to avoid characters &
.
Value attributes contains &
. The way to represent this lexically in XML is to write it as &
. If you parse the XML and set, say, the value of an attribute as a string, you can see that it has been correctly decoded by the parser.
You can think of it the same way you avoid special characters in a Java or C ++ string by using a backslash. The string value does not contain backslashes, but you must use them to represent lexically some special characters.
source to share