Serialize an object to XML

后端 未结 17 1876
渐次进展
渐次进展 2020-11-22 04:41

I have a C# class that I have inherited. I have successfully \"built\" the object. But I need to serialize the object to XML. Is there an easy way to do it?

It looks

17条回答
  •  囚心锁ツ
    2020-11-22 05:31

    my work code. Returns utf8 xml enable empty namespace.

    // override StringWriter
    public class Utf8StringWriter : StringWriter
    {
        public override Encoding Encoding => Encoding.UTF8;
    }
    
    private string GenerateXmlResponse(Object obj)
    {    
        Type t = obj.GetType();
    
        var xml = "";
    
        using (StringWriter sww = new Utf8StringWriter())
        {
            using (XmlWriter writer = XmlWriter.Create(sww))
            {
                var ns = new XmlSerializerNamespaces();
                // add empty namespace
                ns.Add("", "");
                XmlSerializer xsSubmit = new XmlSerializer(t);
                xsSubmit.Serialize(writer, obj, ns);
                xml = sww.ToString(); // Your XML
            }
        }
        return xml;
    }
    

    Example returns response Yandex api payment Aviso url:

    
    

提交回复
热议问题