How to make System.Web XmlSerializer serializer encode quotes c#

765 Views Asked by At

I have the following test case:

    [TestMethod]
    public void SimpleEncodingTest()
    {
        var report = new SimpleReport{Title = @"[quote]""[/quote] [apo]'[/apo] [smaller]<[/smaller] [bigger]>[/bigger] [and]&[/and]" };


        XmlSerializer xsSubmit = new XmlSerializer(typeof(SimpleReport));

        var xml = "";

        using (var sww = new StringWriter())
        {
            using (XmlWriter writer = XmlWriter.Create(sww, new XmlWriterSettings
            {
                Encoding = Encoding.Default
            }))
            {
                xsSubmit.Serialize(writer, report);
                xml = sww.ToString(); // Your XML
            }
        }


    }

I want all special characters including the quotes at apostrophe to be included as such:

    <?xml version="1.0" encoding="utf-16" ?>
    <SimpleReport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <Title>[quote]&quot;[/quote] [apo]&apos;[/apo] [smaller]&lt;[/smaller] [bigger]&gt;[/bigger] [and]&amp;[/and]</Title>
    </SimpleReport>

With the title being "[quote]"[/quote] [apo]'[/apo] [smaller]<[/smaller] [bigger]>[/bigger] [and]&[/and]"

Instead I get:

    <?xml version="1.0" encoding="utf-16" ?>
    <SimpleReport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <Title>[quote]"[/quote] [apo]'[/apo] [smaller]&lt;[/smaller] [bigger]&gt;[/bigger] [and]&amp;[/and]</Title>
    </SimpleReport>

And the title is [/quote] [apo]'[/apo] [smaller]<[/smaller] [bigger]>[/bigger] [and]&[/and].

How do I tell the serializer that I have quotes and apostrophes encoded as well?

PS: I know you don't typically need to encode these characters but this is a client requirement.

Attempts:

1

There are 1 best solutions below

7
Patrick Beynio On

How? Since they are not in an attribute, tell your client you encoded them in UTF16 - wich you did. Otherwise you can usually use the SecurityElement.Escape(String) Method to escape a string, wich will lead to double escaping here. Sadly even doing the

" -> &quot;
' -> &apos;

transitions your self, by

Title = text.Replace("\"", "&quot;").Replace("'", "&apos;")

leads to double quotation... But at least as far as i know these are the only ones not automatically escaped between XML nodes, since they are valid at that point. So I'd think it's not possible the way your customer wants it. at least not with standardized serializers. Sorry