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

后端 未结 4 830
伪装坚强ぢ
伪装坚强ぢ 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: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());
        }
    }
    

提交回复
热议问题