Can I Serialize XML straight to a string instead of a Stream with C#?

*爱你&永不变心* 提交于 2019-12-17 17:56:07

问题


This example uses a StringWriter to hold the serialized data, then calling ToString() gives the actual string value:

Person john = new Person();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person));
StringWriter stringWriter = new StringWriter();
xmlSerializer.Serialize(stringWriter, john);
string serializedXML = stringWriter.ToString();

Is there any easier/Cleaner way to do this? All of the Serialize() overloads seem to use a Stream or Writer.

UPDATE: Asked a similar question about serializing an IEnumerable via an Extension Method .


回答1:


Fun with extension methods...

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);
    }
}



回答2:


More or less your same solution, just using an extension method:

static class XmlExtensions {

    // serialize an object to an XML string
    public static string ToXml(this object obj) {
        // remove the default namespaces
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add(string.Empty, string.Empty);
        // serialize to string
        XmlSerializer xs = new XmlSerializer(obj.GetType());
        StringWriter sw = new StringWriter();
        xs.Serialize(sw, obj, ns);
        return sw.GetStringBuilder().ToString();
    }

}

[XmlType("Element")]
public class Element {
    [XmlAttribute("name")]
    public string name;
}

class Program {
    static void Main(string[] args) {
        Element el = new Element();
        el.name = "test";
        Console.WriteLine(el.ToXml());
    }
}



回答3:


I created this helper method, but I haven't tested it yet. Updated the code per orsogufo's comments (twice):

private string ConvertObjectToXml(object objectToSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());
    StringWriter stringWriter = new StringWriter();

    xmlSerializer.Serialize(stringWriter, objectToSerialize);

    return stringWriter.ToString();
}



回答4:


Seems like no body actually answered his question, which is no, there is no way to generate an XML string without using a stream or writer object.



来源:https://stackoverflow.com/questions/1138414/can-i-serialize-xml-straight-to-a-string-instead-of-a-stream-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!