如何使用TimeSpan和通用列表将对象序列化为C#中的XML?

ATD*_*per 8 c# xml-serialization

我尝试使用XmlSerializer,但XmlSerializer不会序列化TimeSpan值; 它只是为timepans生成一个空标签(否则本来就是完美的).

所以我尝试使用SoapFormatter,但SoapFormatter不会序列化通用列表; 这只会导致例外.

我还有其他选择吗?我不能对我正在序列化的对象的类进行任何更改,因为它是从服务引用生成的.因此,涉及更改课程的任何变通方法都已淘汰.

除了实现自定义序列化器,我别无选择吗?我可以使用任何外部工具吗?

Nic*_*nko 6

您可以使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)

结果:

<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>
Run Code Online (Sandbox Code Playgroud)