Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the XmlSerializer escape special chars like &?

I'm trying to refactor a library that's transmits it's object as XML. Although I think the XmlSerialzer of the .NET Framework can handle the serialization, the class all have a ToXML function. In it all string values are being put through a function that escapes characters like & and alike.

Does the XmlSerializer not escape those kind a characters automatically?

like image 675
Norbert B. Avatar asked Aug 12 '09 13:08

Norbert B.


People also ask

What characters must be escaped in XML?

XML escape characters There are only five: " &quot; ' &apos; < &lt; > &gt; & &amp; Escaping characters depends on where the special character is used. The examples can be validated at the W3C Markup Validation Service.

How do you pass special characters in XML?

To include special characters inside XML files you must use the numeric character reference instead of that character. The numeric character reference must be UTF-8 because the supported encoding for XML files is defined in the prolog as encoding="UTF-8" and should not be changed.

Is a Escape character?

In computing and telecommunication, an escape character is a character that invokes an alternative interpretation on the following characters in a character sequence. An escape character is a particular case of metacharacters.


1 Answers

Yes it does.

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml;

namespace TestXmlSerialiser
{
    public class Person
    {
        public string Name;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            person.Name = "Jack & Jill";

            XmlSerializer ser = new XmlSerializer(typeof(Person));

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            using (XmlWriter writer = XmlWriter.Create(Console.Out, settings))
            {
                ser.Serialize(writer, person);
            }
        }
    }
}

returns

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Jack &amp; Jill</Name>
</Person>
like image 115
Mark Glasgow Avatar answered Sep 19 '22 17:09

Mark Glasgow