我有一个在 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?
最佳答案
确实,这看起来像是处理根名称的错误。解决方法:手动控制根目录:
[XmlRoot("foo")]
public class MyRoot {
[XmlElement("bar")]
public List<RemoteHost> Hosts {get;set;}
}
这应该序列化为
<foo><bar>...</bar>...</foo>
在任一平台上。将 foo
和 bar
替换为您喜欢的名称。
(不过就我个人而言,我会使用二进制输出;p)
关于c# - XmlSerializer 在 .NET 3.5 和 CF.NET 3.5 之间有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6305863/