Click here to Skip to main content
15,901,373 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI,every one i want to save multiple records in xml using c# but when i try to insert new record it's overwrite on existance record i don;t know about xml so plz help me on this topic.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO; 
  

namespace xmlexampleapplication
{
    public class Savexml
    {
        public static void savedata(object obj, string filename)
        {

            XmlSerializer sr = new XmlSerializer(obj.GetType());
            TextWriter writer = new StreamWriter(filename);
            sr.Serialize(writer,obj);
            writer.Close();
        }
    }
}



C#
using System;
using System.Collections.Generic;
using System.Linq;
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; }
        }
    }
}



C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;


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);
            }
        }
    }
}
Posted
Updated 5-Nov-13 5:28am
v2

Well, yes. It will.
Since your SaveXml class create a new file each time, that destroys any existing data rather tan adding anything to it.
To add data to an existing XML file, you would need to read the existing data, add the new to it, and then save the modified version.
 
Share this answer
 
Using the XmlSerializer like you do will always save only one instance of the object type.
If you want to save more than one "Information" object, you can use the XmlSerializer on a List<Information>

1) unserialize the list.
2) append the new record in the list
3) serialize the new list.

It's not the most efficient way, but it should be the closest way of your existing code.

Here is an code sample:
C#
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;

namespace XmlSer
{
    public class Information
    {
        private string m_data;
        public string data
        {
            get { return m_data; }
            set { m_data = value; }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Information info = new Information();
                info.data = System.DateTime.Now.ToShortDateString() + " " + System.DateTime.Now.ToShortTimeString();
                AppendData(info, "data.xml");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        static void AppendData(Information obj, string filename)
        {
            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);
            using (Stream s = File.OpenWrite(filename))
            {
                xmlser.Serialize(s, list);
            }
        }
    }
}
 
Share this answer
 
v2
i used this but still situation is same may me i m wrong any way here is code.


C#
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; }
        }
    }


C#
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);
            }
        }



XML
public static void savedata(Information obj, string filename)
        {

           
            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);
            using (Stream s = File.OpenWrite(filename))
            {
                xmlser.Serialize(s, list);
            }

        }
 
Share this answer
 
v2
Comments
Pascal-78 5-Nov-13 11:31am    
The XML used in this version is not compatible with the file generated the first time. That means the first time the file cannot be deserialized to a list and a new list will be created.

Did you try to debug your program and look in the unserialized list?
Did you try to click on your save button twice?

By the way, this is not a solution, you should have used the "Have a Question or Comment?" button (like the way I added this comment.)
Hi,
This is my Code Snippet For this Problem.
If their is any Query then feel free to ask me .



public partial class Register : System.Web.UI.Page
{
    //declare static vaaible to holds the node values
    static string name;
    static string pswd;
    static string age;
    static string mobile;
    static XmlNode root;
    static XmlNode xn; XmlDocument xdoc; 
//Page Load
protected void Page_Load(object sender, EventArgs e)
    {
        lblErrorPswd.Visible = false;
        name = txtUname.Text;
        pswd = string.Empty;
        if (txtPswd.Text == txtCpswd.Text)
        {
            pswd = txtPswd.Text;
        }
        age = txtAge.Text;
        mobile = txtMobile.Text;
    }
protected void butRegister_Click(object sender, EventArgs e)
    {
   string xmlpath = @"C:\Users\Trainee\Documents\Visual Studio 2012\WebSites\xmlLoginApp\XMlRegister.xml";

xdoc = new XmlDocument();
        if (File.Exists(xmlpath))
        {
     xdoc.Load(xmlpath);
            {
        XmlNodeList xnodelist = xdoc.GetElementsByTagName("logindetails");
                foreach(XmlNode xnode in xnodelist)
                {
                    xn = xnode.LastChild.OwnerDocument.FirstChild;
                }
                AppendXml(xn);
                xdoc.Save(xmlpath);
                Response.Redirect("login.aspx");
            }
        }

        else
        {
            XmlDeclaration xdeclartion = xdoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
            root = xdoc.CreateElement("logindetails");
            xdoc.AppendChild(root);
            AppendXml(root);
            xdoc.Save(xmlpath);
            Response.Redirect("login.aspx");
        }

protected void AppendXml(XmlNode root)
    {
        XmlNode person = xdoc.CreateElement("person");
        root.AppendChild(person);
        XmlNode uname = xdoc.CreateElement("uname");
        uname.InnerText = name;
        person.AppendChild(uname);
        XmlNode psswd = xdoc.CreateElement("pswd");
        psswd.InnerText = pswd;
        person.AppendChild(psswd);
       }
 
Share this answer
 
v2
Comments
Rishi Gaur 27-May-14 8:17am    
Hi, Anurag Prajesh, This is helpful answer, please submit such type of article in future.
Anurag Prajesh 27-May-14 8:18am    
Thank you Rishi
It was so nice of You
I am Glad you liked this
Member 10846839 27-May-14 8:21am    
Good one Anurag, Keep it up.
Anurag Prajesh 2-Dec-14 0:09am    
Thanku

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900