c# - 如何在 C# 中将具有 TimeSpan 和通用列表的对象序列化为 XML?

标签 c# xml-serialization

我尝试使用 XmlSerializer,但 XmlSerializer 不会序列化 TimeSpan 值;它只是为时间跨度生成一个空标签(否则就完美了)。

然后我尝试使用 SoapFormatter,但是 SoapFormatter 不会序列化通用列表;这只会导致异常。

我还有哪些其他选择?我无法对正在序列化的对象的类进行任何更改,因为它是从服务引用生成的。因此,任何涉及更改类的解决方法都已失效。

我别无选择,只能实现自定义序列化程序吗?有没有我可以使用的外部工具?

最佳答案

您可以使用 DataContractSerializer


[DataContract]
public class TestClass
{
    // You can use List<T> or other generic collection
    [DataMember]
    public HashSet<int> h { get; set; }

    [DataMember]
    public TimeSpan t { get; set; }

    public TestClass()
    {
        h = new HashSet<int>{1,2,3,4};
        t = TimeSpan.FromDays(1);
    }
}

var o = new TestClass();

ms = new MemoryStream();

var sr = new DataContractSerializer(typeof(TestClass));
sr.WriteObject(ms, o);

File.WriteAllBytes("test.xml", ms.ToArray());

ms = new MemoryStream(File.ReadAllBytes("test.xml"));

sr = new DataContractSerializer(typeof(TestClass));
var readObject = (TestClass)sr.ReadObject(ms);

结果:

<TestClass xmlns="http://schemas.datacontract.org/2004/07/Serialization" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><h xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"><a:int>1</a:int><a:int>2</a:int><a:int>3</a:int><a:int>4</a:int></h><t>P1D</t></TestClass>

关于c# - 如何在 C# 中将具有 TimeSpan 和通用列表的对象序列化为 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4196098/

相关文章:

c# - 关于实现工厂类型类的建议

java - 哪个是 Java 序列化的最佳替代方案?

java - 使用 xstream 自定义 java 集合的序列化

c# - 是否可以为 path.Data 设置动画

c# - 如何在 ASP.NET 4 WebForm 应用程序中使用 AppDomains?

.net - 有没有办法让 xsd.exe 生成范围为 "internal"的类?

c# - 有什么方法可以阻止在编译时调用的方法吗?

c# - 在 xml 序列化期间忽略属性,但在反序列化期间不忽略

c# - 如何正确处理等待句柄

c# - 定时器速度问题WPF