ADDING MULTIPLE RECORDS TO THE XML FILE

Tanuj Kumar

Total Post:134

Points:940
Posted by  Tanuj Kumar
C# 
C#
 951  View(s)
Ratings:
Rate this:

I would like to add multiple records to the xml file and here is the code which I’m using,

XmlTextWriter xwriter = new XmlTextWriter("C:\\Users\\Desktop\\TestFolder\\Xdoc1.xml", Encoding.UTF8);

xwriter.Formatting = Formatting.Indented;

xwriter.WriteStartElement("Employee");

xwriter.WriteStartElement("Person");

xwriter.WriteStartElement("Name");

xwriter.WriteString(textBox1.Text);

xwriter.WriteEndElement();

xwriter.WriteStartElement("Designation");

xwriter.WriteString(textBox2.Text);

xwriter.WriteEndElement();

xwriter.WriteStartElement("Employee ID");

xwriter.WriteString(textBox3.Text);

xwriter.WriteEndElement();

xwriter.WriteStartElement("Email");

xwriter.WriteString(textBox4.Text);

xwriter.WriteEndElement();

xwriter.WriteEndElement();

xwriter.WriteEndElement();

xwriter.Close();

The problem with this code is that only one record can be added. When i try to add the 2nd record, the previous record is overwritten.

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: Adding multiple Records to the XML file

    Hi Tanuj,


    Here is no need to convert xmlWriter class.

    string xmlFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Candidates.xml");

    xmldoc = new XmlDocument();

    xmldoc.Load(xmlFile);

    root = xmldoc.DocumentElement;

    try

    {

    XmlNode CandidateNode = xmldoc.CreateNode(XmlNodeType.Element, "Candidate", "");

    XmlNode id = xmldoc.CreateNode(XmlNodeType.Element, "CandidateId", "");

    id.InnerText = "1";

    CandidateNode.AppendChild(id);

    XmlNode subPositionId = xmldoc.CreateNode(XmlNodeType.Element, "SubPositionId", "");

    subPositionId.InnerText = candidate.PositionId.ToString();

    CandidateNode.AppendChild(subPositionId);

    XmlNode firstName = xmldoc.CreateNode(XmlNodeType.Element, "FirstName", "");

    firstName.InnerText = candidate.FirstName;

    XmlNode lastName = xmldoc.CreateNode(XmlNodeType.Element, "LastName", "");

    lastName.InnerText = candidate.LastName;

    CandidateNode.AppendChild(firstName);

    CandidateNode.AppendChild(lastName);

    root.AppendChild(CandidateNode);

    xmldoc.Save(xmlFile);

    This will help you.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!