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 " &amp;

":

<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&amp;end=2015-06-04&amp;id=174511&amp;adults=2&amp;childAges=0&amp;room=1"/>
</Rate>
</RateList>

      

How can I avoid this change in my answer?

Thanks in advance.

+3


source to share


2 answers


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 &amp;

. 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.

+2


source


You have two conflicting requirements:

(a) the output must be XML



(b) the output must contain a non-isolated "&"

XML cannot contain unlimited ampersands.

0


source







All Articles