views:

334

answers:

2

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?

A: 

All of the .NET XML APIs naturally understand the rules of XML. If necessary, they will change < into &lt; etc.

John Saunders
+2  A: 

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"&gt;
  <Name>Jack &amp; Jill</Name>
</Person>
Mark Glasgow