Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlSerializer differs between .NET 3.5 & CF.NET 3.5

I've a library that turns under CF.NET & .NET but serialization differs between both. As a result, a XML file generated under CF.NET isn't readable under .NET, and that is a big problem for me !

Here the code sample :

[Serializable, XmlRoot("config")]
public sealed class RemoteHost : IEquatable<RemoteHost>
{
    // ...
}

public class Program
{
    public static void Main()
    {
        RemoteHost host = new RemoteHost("A");
        List<RemoteHost> hosts = new List<RemoteHost>();
        hosts.Add(host);
        XmlSerializer ser = new XmlSerializer(typeof(List<RemoteHost>));
        ser.Serialize(Console.Out, hosts);
    }
}

CF.NET xml :

<?xml version="1.0"?>
<ArrayOfConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <config Name="A">
  </config>
</ArrayOfConfig>

.NET xml

<?xml version="1.0" encoding="ibm850"?>
<ArrayOfRemoteHost xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <RemoteHost Name="A">
  </RemoteHost>
</ArrayOfRemoteHost>

How can I modify my program in order to generate the same XML ?

like image 219
Arnaud F. Avatar asked Jun 10 '11 11:06

Arnaud F.


1 Answers

It looks like a bug processing the root name, indeed. As a workaround: take control of the root manually:

[XmlRoot("foo")]
public class MyRoot {
    [XmlElement("bar")]
    public List<RemoteHost> Hosts {get;set;}
}

This should serialize as

<foo><bar>...</bar>...</foo>

on either platform. Substitute foo and bar for your preferred names.

(personally, I'd be using binary output, though ;p)

like image 199
Marc Gravell Avatar answered Sep 30 '22 19:09

Marc Gravell