Serialize an object to XML

后端 未结 17 1892
渐次进展
渐次进展 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:10

    You can use the function like below to get serialized XML from any object.

    public static bool Serialize<T>(T value, ref string serializeXml)
    {
        if (value == null)
        {
            return false;
        }
        try
        {
            XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
            StringWriter stringWriter = new StringWriter();
            XmlWriter writer = XmlWriter.Create(stringWriter);
    
            xmlserializer.Serialize(writer, value);
    
            serializeXml = stringWriter.ToString();
    
            writer.Close();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    

    You can call this from the client.

    0 讨论(0)
  • 2020-11-22 05:13

    I will start with the copy answer of Ben Gripka:

    public void Save(string FileName)
    {
        using (var writer = new System.IO.StreamWriter(FileName))
        {
            var serializer = new XmlSerializer(this.GetType());
            serializer.Serialize(writer, this);
            writer.Flush();
        }
    }
    

    I used this code earlier. But reality showed that this solution is a bit problematic. Usually most of programmers just serialize setting on save and deserialize settings on load. This is an optimistic scenario. Once the serialization failed, because of some reason, the file is partly written, XML file is not complete and it is invalid. In consequence XML deserialization does not work and your application may crash on start. If the file is not huge, I suggest first serialize object to MemoryStream then write the stream to the File. This case is especially important if there is some complicated custom serialization. You can never test all cases.

    public void Save(string fileName)
    {
        //first serialize the object to memory stream,
        //in case of exception, the original file is not corrupted
        using (MemoryStream ms = new MemoryStream())
        {
            var writer = new System.IO.StreamWriter(ms);    
            var serializer = new XmlSerializer(this.GetType());
            serializer.Serialize(writer, this);
            writer.Flush();
    
            //if the serialization succeed, rewrite the file.
            File.WriteAllBytes(fileName, ms.ToArray());
        }
    }
    

    The deserialization in real world scenario should count with corrupted serialization file, it happens sometime. Load function provided by Ben Gripka is fine.

    public static [ObjectType] Load(string fileName)
    {
        using (var stream = System.IO.File.OpenRead(fileName))
        {
            var serializer = new XmlSerializer(typeof([ObjectType]));
            return serializer.Deserialize(stream) as [ObjectType];        
        }    
    }
    

    And it could be wrapped by some recovery scenario. It is suitable for settings files or other files which can be deleted in case of problems.

    public static [ObjectType] LoadWithRecovery(string fileName)
    {
        try
        {
            return Load(fileName);
        }
        catch(Excetion)
        {
            File.Delete(fileName); //delete corrupted settings file
            return GetFactorySettings();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:14

    To serialize an object, do:

     using (StreamWriter myWriter = new StreamWriter(path, false))
     {
         XmlSerializer mySerializer = new XmlSerializer(typeof(your_object_type));
         mySerializer.Serialize(myWriter, objectToSerialize);
     }
    

    Also remember that for XmlSerializer to work, you need a parameterless constructor.

    0 讨论(0)
  • 2020-11-22 05:17

    I have a simple way to serialize an object to XML using C#, it works great and it's highly reusable. I know this is an older thread, but I wanted to post this because someone may find this helpful to them.

    Here is how I call the method:

    var objectToSerialize = new MyObject();
    var xmlString = objectToSerialize.ToXmlString();
    

    Here is the class that does the work:

    Note: Since these are extension methods they need to be in a static class.

    using System.IO;
    using System.Xml.Serialization;
    
    public static class XmlTools
    {
        public static string ToXmlString<T>(this T input)
        {
            using (var writer = new StringWriter())
            {
                input.ToXml(writer);
                return writer.ToString();
            }
        }
    
        private static void ToXml<T>(this T objectToSerialize, StringWriter writer)
        {
            new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:17
    public string ObjectToXML(object input)
    {
        try
        {
            var stringwriter = new System.IO.StringWriter();
            var serializer = new XmlSerializer(input.GetType());
            serializer.Serialize(stringwriter, input);
            return stringwriter.ToString();
        }
        catch (Exception ex)
        {
            if (ex.InnerException != null)
                ex = ex.InnerException;
    
            return "Could not convert: " + ex.Message;
        }
    }
    
    //Usage
    var res = ObjectToXML(obj)
    

    You need to use following classes:

    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;
    
    0 讨论(0)
  • 2020-11-22 05:20

    You have to use XmlSerializer for XML serialization. Below is a sample snippet.

     XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
     var subReq = new MyObject();
     var xml = "";
    
     using(var sww = new StringWriter())
     {
         using(XmlWriter writer = XmlWriter.Create(sww))
         {
             xsSubmit.Serialize(writer, subReq);
             xml = sww.ToString(); // Your XML
         }
     }
    
    0 讨论(0)
提交回复
热议问题