可以将XML直接序列化为字符串而不是C#的Stream吗?

前端之家收集整理的这篇文章主要介绍了可以将XML直接序列化为字符串而不是C#的Stream吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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);
    }
}

猜你在找的XML相关文章