Steen
Steen

Reputation: 2887

XML serialization national chars error

EDIT:

Doing too much.... this works for me with national chars

                var xs = new XmlSerializer(typeof(ToDoItem));
                var stringWriter = new StringWriter();
                xs.Serialize(stringWriter, item);
                var test = XDocument.Parse(stringWriter.ToString());

...where The item is the object containing strings with national chars

/EDIT

I did a project with serialization of some objects.

I copied some code from examples on this site and everything worked great, till I changed framework ASP.NET from 3.5 til 4.0... (and changed ISS7 .net setting from v2.0 to v4.0)

I am 99% sure this is the cause of the following error:

Before this change something like this:

                var test = XDocument.Parse(SerializeObject("æøåAØÅ", typeof(string)));
                test.Save(HttpContext.Current.Server.MapPath("test.xml"));

Would save the xml with the exact chars used.

Now it saves this: ���A��

I would like: Information on settings I might have to make in IIS7

OR

A comment on how to change the serializing methods to handle the national chars better.

This is the serialization code used.

  private static String UTF8ByteArrayToString(Byte[] characters)
    {
        var encoding = new UTF8Encoding();

        String constructedString = encoding.GetString(characters);

        return (constructedString);
    }



    public static String SerializeObject(Object pObject, Type type)
    {
        try
        {
            String XmlizedString = null;
            var memoryStream = new MemoryStream();
            var xs = new XmlSerializer(type);
            var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.ASCII);


            xs.Serialize(xmlTextWriter, pObject);
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
            return XmlizedString.Trim();
        }

        catch (Exception e)
        {
            //Console.WriteLine(e);

            return null;
        }
    }

Upvotes: 0

Views: 250

Answers (1)

svick
svick

Reputation: 245046

You save a text as using ASCII and then decode it using UTF-8 and expect that it will work? It won't. This code could never work properly, regardless of any updates or settings.

There is no need to write the XML to a MemoryStream and then decode that. Just use StringWriter:

var xs = new XmlSerializer(type);
var stringWriter = new StringWriter();
xs.Serialize(stringWriter, pObject);
return stringWriter.ToString();

Upvotes: 1

Related Questions