要将TimeSpan序列化为XML,您可以使用C#的内置XML序列化器,例如XmlSerializer类。以下是一个简单的示例,说明如何将TimeSpan对象序列化为XML字符串,并将其反序列化为TimeSpan对象。
首先,定义一个包含TimeSpan属性的类:
using System;
public class TimeSpanData
{
public TimeSpan TimeSpanValue { get; set; }
}
接下来,创建一个TimeSpanData对象,并将其序列化为XML字符串:
using System;
using System.IO;
using System.Xml.Serialization;
public class TimeSpanData
{
public TimeSpan TimeSpanValue { get; set; }
}
public class Program
{
public static void Main()
{
TimeSpanData data = new TimeSpanData { TimeSpanValue = new TimeSpan(1, 2, 3, 4, 5) };
XmlSerializer serializer = new XmlSerializer(typeof(TimeSpanData));
using StringWriter writer = new StringWriter();
serializer.Serialize(writer, data);
string xmlString = writer.ToString();
Console.WriteLine("Serialized XML:");
Console.WriteLine(xmlString);
}
}
这将输出以下XML字符串:
<?xml version="1.0" encoding="utf-16"?>
<TimeSpanData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<TimeSpanValue>P1DT2H3M4.005S</TimeSpanValue>
</TimeSpanData>
最后,反序列化XML字符串为TimeSpanData对象:
using System;
using System.IO;
using System.Xml.Serialization;
public class TimeSpanData
{
public TimeSpan TimeSpanValue { get; set; }
}
public class Program
{
public static void Main()
{
TimeSpanData data = new TimeSpanData { TimeSpanValue = new TimeSpan(1, 2, 3, 4, 5) };
XmlSerializer serializer = new XmlSerializer(typeof(TimeSpanData));
using StringWriter writer = new StringWriter();
serializer.Serialize(writer, data);
string xmlString = writer.ToString();
Console.WriteLine("Serialized XML:");
Console.WriteLine(xmlString);
using StringReader reader = new StringReader(xmlString);
TimeSpanData deserializedData = (TimeSpanData)serializer.Deserialize(reader);
Console.WriteLine("Deserialized TimeSpanData:");
Console.WriteLine($"TimeSpanValue: {deserializedData.TimeSpanValue}");
}
}
这将输出以下内容:
Serialized XML:
<?xml version="1.0" encoding="utf-16"?>
<TimeSpanData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<TimeSpanValue>P1DT2H3M4.005S</TimeSpanValue>
</TimeSpanData>
Deserialized TimeSpanData:
TimeSpanValue: 1.02:03:04.0050000
这样,您就可以将TimeSpan对象序列化为XML字符串,并将其反序列化为TimeSpan对象。
领取专属 10元无门槛券
手把手带您无忧上云