0

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:

4

1 回答 1

0

如何?由于它们不在属性中,因此请告诉您的客户您使用 UTF16 对它们进行了编码 - 您就是这样做的。否则,您通常可以使用SecurityElement.Escape(String)Method 来转义字符串,这将导致此处出现双重转义。可悲的是,即使这样做

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

转变你的自我,通过

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

导致双引号......但至少据我所知,这些是唯一不会在 XML 节点之间自动转义的,因为它们在那时是有效的。所以我认为这不可能是您的客户想要的方式。至少不是标准化的序列化程序。对不起

于 2020-02-24T14:04:14.370 回答