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

后端 未结 4 810
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 10:39

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

P         


        
相关标签:
4条回答
  • 2020-12-08 11:20

    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();
    }
    
    0 讨论(0)
  • 2020-12-08 11:27

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-08 11:34

    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.

    0 讨论(0)
  • 2020-12-08 11:41

    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());
        }
    }
    
    0 讨论(0)
提交回复
热议问题