XmlSerializer differs between .NET 3.5 & CF.NET 3.5

本文关键字:NET CF amp XmlSerializer differs between | 更新日期: 2023-09-27 17:58:47

我有一个在CF.NET&下运行的库。NET,但两者的序列化不同。因此,在CF.NET下生成的XML文件在.NET下不可读,这对我来说是个大问题!

这里的代码示例:

[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>

如何修改程序以生成相同的XML?

XmlSerializer differs between .NET 3.5 & CF.NET 3.5

实际上,这看起来像是一个处理根名称的错误。作为一种变通方法:手动控制根:

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

这应该序列化为

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

在任一平台上。用foobar替换您喜欢的名称。

(就我个人而言,我会使用二进制输出;p)