Home > DeveloperSection > Forums > Adding multiple Records to the XML file
Tanuj Kumar

Total Post:134

Points:940
Posted on    September-04-2013 1:52 AM

 C# C# 
Ratings:


 1 Reply(s)
 744  View(s)
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.



Sumit Kesarwani

Total Post:378

Points:2694
Posted on    September-04-2013 6:57 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick