0

I am trying to write the user input data to the XML file in asp.net/C#. the data will type in textbox.

The C# code:

int i = 0;
protected void submit(object sender,EventArgs e)
{
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(Server.MapPath("~/XMLFile1.xml"));
    Console.WriteLine(xdoc);
    XmlElement contact = xdoc.CreateElement("Contact");

    XmlAttribute Count = xdoc.CreateAttribute("Count");
    i = i + 1;
    Count.Value = i.ToString();

    XmlElement Name = xdoc.CreateElement("Name");
    XmlText xmlName = xdoc.CreateTextNode(name.Text);

    XmlElement EmailId = xdoc.CreateElement("EmailId");
    XmlText xmlemail = xdoc.CreateTextNode(emailId.Text);

    XmlElement Comments = xdoc.CreateElement("Comments");
    XmlText xmlcomment = xdoc.CreateTextNode(comments.Text);

    Name.AppendChild(xmlName);
    EmailId.AppendChild(xmlemail);
    Comments.AppendChild(xmlcomment);

    contact.Attributes.Append(Count);
    contact.AppendChild(Name);
    contact.AppendChild(EmailId);
    contact.AppendChild(Comments);

    xdoc.DocumentElement.AppendChild(contact);

    xdoc.Save(Server.MapPath("~/XMLFile1.xml"));

    Response.Redirect(Request.Url.AbsoluteUri);
}

No errors are displaying not storing the values.

Dilsha.P
  • 15
  • 3
  • Note that in ASP.Net you will need some kind of synchronization on the file to deal with concurrent reads/writes. A DB or unique files would fix this. – Alex K. Jun 25 '19 at 11:05
  • You are reading & writing the same file. Please explain what you are trying to acheive – Nareen Babu Jun 25 '19 at 11:10
  • https://stackoverflow.com/questions/3875131/c-sharp-adding-data-to-xml-file, https://stackoverflow.com/questions/7931650/adding-elements-to-an-xml-file-in-c-sharp, https://stackoverflow.com/questions/20922835/appending-an-existing-xml-file-with-xmlwriter – xdtTransform Jun 25 '19 at 11:29

1 Answers1

0

Hope in the below code, runtime error was throwing.

xdoc.Load(Server.MapPath("~/XMLFile1.xml"));

2 reasons for the error.

  1. XMLFile1.xml not available in the root directory.
  2. Basic xml structure not available in the xml file.

Basic xml structure:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>

</Contacts>
Skaria Thomas
  • 419
  • 3
  • 10