This example使用StringWriter来保存序列化数据,然后调用ToString()给出实际的字符串值:
Person john = new Person(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person)); StringWriter stringWriter = new StringWriter(); xmlSerializer.Serialize(stringWriter,john); string serializedXML = stringWriter.ToString();
有没有更简单/更清洁的方式来做到这一点?所有的Serialize()重载似乎都使用Stream或Writer。
更新:询问有关serializing an IEnumerable via an Extension Method的类似问题。
有扩展方法的乐趣…
var ret = john.ToXmlString()
public static class XmlTools { public static string ToXmlString<T>(this T input) { using (var writer = new StringWriter()) { input.ToXml(writer); return writer.ToString(); } } public static void ToXml<T>(this T objectToSerialize,Stream stream) { new XmlSerializer(typeof(T)).Serialize(stream,objectToSerialize); } public static void ToXml<T>(this T objectToSerialize,StringWriter writer) { new XmlSerializer(typeof(T)).Serialize(writer,objectToSerialize); } }