Saturday 15 September 2012

creating and adding data to xml



//creating xml document if not exists

  if (!File.Exists(HttpContext.Current.Server.MapPath("~/UploadFile/" + Session["Name"].ToString()) + ".xml"))
            {
                XmlTextWriter xtw = new XmlTextWriter(HttpContext.Current.Server.MapPath("~/UploadFile/" + Session["Name"].ToString()) + ".xml", System.Text.Encoding.UTF8);
                xtw.WriteStartDocument(true);
                xtw.WriteStartElement("root");
                xtw.WriteStartElement("File");
                xtw.WriteElementString("FileName", System.IO.Path.GetFileName( FileUploadProof.PostedFile.FileName));
                xtw.WriteElementString("UploadedDate", DateTime.Now.Date.ToShortDateString());
                xtw.WriteElementString("FileType", ddlProofType.SelectedItem.Text.Trim());
                xtw.WriteEndElement();
                xtw.WriteEndDocument();
                xtw.Close();

            }
            else
            {
//adding info to xml
                XmlDocument doc = new XmlDocument();
                doc.Load(HttpContext.Current.Server.MapPath("~/UploadFile/" + Session["Name"].ToString()) + ".xml");
                XmlElement el = doc.CreateElement("File");

                XmlElement el1 = doc.CreateElement("FileName");
                el1.InnerText =  System.IO.Path.GetFileName(  FileUploadProof.PostedFile.FileName);
                doc.DocumentElement.AppendChild(el).AppendChild(el1);

                XmlElement el2 = doc.CreateElement("UploadedDate");
                el2.InnerText = System.DateTime.Now.Date.ToShortDateString();
                doc.DocumentElement.AppendChild(el).AppendChild(el2);

                XmlElement el3 = doc.CreateElement("FileType");
                el3.InnerText = ddlProofType.SelectedItem.Text;

                doc.DocumentElement.AppendChild(el).AppendChild(el3);

                doc.DocumentElement.AppendChild(el);
                doc.Save(HttpContext.Current.Server.MapPath("~/UploadFile/" + Session["Name"].ToString()) + ".xml");

            }



No comments:

Post a Comment