none
Writing xml file using c# RRS feed

  • Question

  • Hi, every one i wrote xml file using serialize class but my friends says that is not good practice if it's true so how can i write xml file in which i can add multiple records.

    here is my code: I m using separate classes:

    using System.Xml.Serialization;
    using System.IO;
    using System.Xml;
    using System.Xml.XPath;


    namespace xmlexampleapplication
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void btnSave_Click(object sender, EventArgs e)
            {
                try
                {
                    Information info = new Information();
                    info.data1 = textBoxdata1.Text;
                    info.data2 = textBoxdata2.Text;
                    info.data3 = textBoxdata3.Text;

                    Savexml.savedata(info,"data.xml");
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }

    }

    }

    using System.Windows.Forms;

    namespace xmlexampleapplication
    {
        public class Savexml
        {
            public static void savedata(Information obj, string filename)
            {
                if (!File.Exists("data.xml"))
                {
                    XmlSerializer sr = new XmlSerializer(obj.GetType());
                    TextWriter writer = new StreamWriter(filename);
                    sr.Serialize(writer, obj);
                    writer.Close();

                }
                else
                {
                    XmlSerializer xmlser = new XmlSerializer(typeof(List<Information>));
                    List<Information> list = null;
                    try
                    {
                        using (Stream s = File.OpenRead(filename))
                        {
                            list = xmlser.Deserialize(s) as List<Information>;
                           
                           
                        }
                    }
                    catch
                    {
                        list = new List<Information>();
                    }
                    list.Add(obj);
                    MessageBox.Show("" + list);
                    using (Stream s = File.OpenWrite(filename))
                    {
                        xmlser.Serialize(s, list);
                    }
                }

            }
        }
    }

    using System.Text;

    namespace xmlexampleapplication
    {
        public class Information
        {

            private string m_data1;
            private string m_data2;
            private string m_data3;

            public string data1
            {
                get { return m_data1; }
                set { m_data1 = value; }
           
            }
            public string data2
            {
                get { return m_data2; }
                set { m_data2 = value; }

           
           
            }
            public string data3
            {
                get { return m_data3; }
                set { m_data3 = value; }
            }
        }
    }

    Saturday, November 9, 2013 7:30 PM

Answers

  • Hello,

    It depends on the scenario. XmlSerializer is certainly one way, and has the advantage of mapping directly to an object model. In .NET 3.5, XDocument etc are also very friendly. If the size is very large, then XmlWriter is your friend.

    For an XDocument example:

        Console.WriteLine(

            new XElement("Foo",

                new XAttribute("Bar", "some & value"),

                new XElement("Nested", "data")));

    Or the same with XmlDocument:

        XmlDocument doc = new XmlDocument();

        XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Foo"));

        el.SetAttribute("Bar", "some & value");

        el.AppendChild(doc.CreateElement("Nested")).InnerText = "data";

        Console.WriteLine(doc.OuterXml);

    If you are writing a large stream of data, then any of the DOM approaches (such asXmlDocument/XDocument etc) will quickly take a lot of memory. So if you are writing a 100MB xml file from csv, you might consider XmlWriter; this is more primative (a write-once firehose), but very efficient (imagine a big loop here):

        XmlWriter writer = XmlWriter.Create(Console.Out);

        writer.WriteStartElement("Foo");

        writer.WriteAttributeString("Bar", "Some & value");

        writer.WriteElementString("Nested", "data");

        writer.WriteEndElement();

    Finally, via XmlSerializer:

        [Serializable]

        public class Foo

        {

            [XmlAttribute]

            public string Bar { get; set; }

            public string Nested { get; set; }

        }

        ...

        Foo foo = new Foo

        {

            Bar = "some & value",

            Nested = "data"

        };

        new XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo);

    This is a nice model for mapping to classes etc; however, it might be overkill if you are doing something simple (or if the desired xml doesn't really have a direct correlation to the object model). Another issue withXmlSerializer is that it doesn't like to serialize immutable types: everything must have a public getterand setter (unless you do it all yourself by implementing IXmlSerializable, in which case you haven't gained much by using XmlSerializer).

    Here is the original post. http://stackoverflow.com/questions/284324/what-is-the-best-way-to-build-xml-in-c-sharp-code

    Best Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, November 11, 2013 6:02 AM
    Moderator