XmlSerializer在.NET 3.5和Linux之间有所不同。 CF.NET 3.5

时间:2011-06-10 11:41:43

标签: c# .net xml serialization compact-framework

我有一个在CF.NET& .NET但序列化在两者之间有所不同。因此,在.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?

1 个答案:

答案 0 :(得分:4)

确实,它看起来像是处理根名称的错误。解决方法:手动控制root:

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

这应该序列化为

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

在任一平台上。将foobar替换为您的首选名称。

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