2011-06-10 56 views
6

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

下面的代码示例:

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

回答

4

看起来确实是处理根名称的错误。作为一种变通方法:手动采取根的控制:

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

这应该两种平台上作为序列

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

。替换foobar作为您的首选名称。

(个人而言,我会使用二进制输出,虽然; P)

+0

Arghhhhhh ......这样做的方式,我需要调整自己的所有商业模式......二进制输出? – 2011-06-10 11:52:41

+0

@Arnaud - 只是在序列化的时候添加一个包装并不能真正改变整个模型。 – 2011-06-10 11:55:17

+0

我需要将所有RemoteHost添加到MyRoot,如果我想序列化它们,将会看到... – 2011-06-10 12:05:18