Bishop
Bishop

Reputation: 296

How can I add specific escape characters to xmlserializer?

I have a method that serializes an object to xml and returns the string:

public static string SerializeType<T>(T item)
    {
        var serializer = new XmlSerializer(typeof(T));
        var builder = new StringBuilder();
        var settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        using (var stringWriter = XmlWriter.Create(builder, settings))
        {
            serializer.Serialize(stringWriter, item);
            return builder.ToString();
        }
    }

However, it is not removing all the reserved characters from strings in objects I pass in. Microsoft lists the Reserved Characters as <>&% but when I input an item with a "abc&cd%d" string field, it spits out "a &lt ;ab&gt ;bc&amp ;cd%d" without out the spaces preceding the semicolons. % is not being escaped. How can I add the correct escape sequence for percent? The % causes an error when I send it to a client's app. The escaping listed on that page fixes the problem.

Upvotes: 0

Views: 672

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500514

% isn't really a reserved character in XML. The documentation you've referred to is for SQL server, and there's a small note under the table:

The Notification Services XML vocabulary reserves the percent sign (%) for denoting parameters.

But you shouldn't expect XmlSerializer (or any other general-purpose XML library) to escape % for you. Unless you're using "Notification Services XML" I wouldn't expect this to be a problem.

Upvotes: 1

Related Questions