Serialize an object to XML

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

    I modified mine to return a string rather than use a ref variable like below.

    public static string Serialize<T>(this T value)
    {
        if (value == null)
        {
            return string.Empty;
        }
        try
        {
            var xmlserializer = new XmlSerializer(typeof(T));
            var stringWriter = new StringWriter();
            using (var writer = XmlWriter.Create(stringWriter))
            {
                xmlserializer.Serialize(writer, value);
                return stringWriter.ToString();
            }
        }
        catch (Exception ex)
        {
            throw new Exception("An error occurred", ex);
        }
    }
    

    Its usage would be like this:

    var xmlString = obj.Serialize();
    
    0 讨论(0)
  • 2020-11-22 05:21

    Extension class:

    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;
    
    namespace MyProj.Extensions
    {
        public static class XmlExtension
        {
            public static string Serialize<T>(this T value)
            {
                if (value == null) return string.Empty;
    
                var xmlSerializer = new XmlSerializer(typeof(T));
    
                using (var stringWriter = new StringWriter())
                {
                    using (var xmlWriter = XmlWriter.Create(stringWriter,new XmlWriterSettings{Indent = true}))
                    {
                        xmlSerializer.Serialize(xmlWriter, value);
                        return stringWriter.ToString();
                    }    
                }
            }
        }
    }
    

    Usage:

    Foo foo = new Foo{MyProperty="I have been serialized"};
    
    string xml = foo.Serialize();
    

    Just reference the namespace holding your extension method in the file you would like to use it in and it'll work (in my example it would be: using MyProj.Extensions;)

    Note that if you want to make the extension method specific to only a particular class(eg., Foo), you can replace the T argument in the extension method, eg.

    public static string Serialize(this Foo value){...}

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

    Based on above solutions, here comes a extension class which you can use to serialize and deserialize any object. Any other XML attributions are up to you.

    Just use it like this:

            string s = new MyObject().Serialize(); // to serialize into a string
            MyObject b = s.Deserialize<MyObject>();// deserialize from a string
    
    
    
    internal static class Extensions
    {
        public static T Deserialize<T>(this string value)
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
    
            return (T)xmlSerializer.Deserialize(new StringReader(value));
        }
    
        public static string Serialize<T>(this T value)
        {
            if (value == null)
                return string.Empty;
    
            var xmlSerializer = new XmlSerializer(typeof(T));
    
            using (var stringWriter = new StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
                {
                    xmlSerializer.Serialize(xmlWriter, value);
                    return stringWriter.ToString();
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:26

    Here's a basic code that will help serializing the C# objects into xml:

    using System;
    
    public class clsPerson
    {
      public  string FirstName;
      public  string MI;
      public  string LastName;
    }
    
    class class1
    { 
       static void Main(string[] args)
       {
          clsPerson p=new clsPerson();
          p.FirstName = "Jeff";
          p.MI = "A";
          p.LastName = "Price";
          System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
          x.Serialize(Console.Out, p);
          Console.WriteLine();
          Console.ReadLine();
       }
    }    
    
    0 讨论(0)
  • 2020-11-22 05:28
        string FilePath = ConfigurationReader.FileLocation;   //Getting path value from web.config            
        XmlSerializer serializer = new XmlSerializer(typeof(Devices)); //typeof(object)
                MemoryStream memStream = new MemoryStream();
                serializer.Serialize(memStream, lstDevices);//lstdevices : I take result as a list.
                FileStream file = new FileStream(folderName + "\\Data.xml", FileMode.Create, FileAccess.ReadWrite); //foldername:Specify the path to store the xml file
                memStream.WriteTo(file);
                file.Close();
    

    You can create and store the result as xml file in the desired location.

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

    It's a little bit more complicated than calling the ToString method of the class, but not much.

    Here's a simple drop-in function you can use to serialize any type of object. It returns a string containing the serialized XML contents:

    public string SerializeObject(object obj)
    {
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
            serializer.Serialize(ms, obj);
            ms.Position = 0;
            xmlDoc.Load(ms);
            return xmlDoc.InnerXml;
        }
    }
    
    0 讨论(0)
提交回复
热议问题