Write XML file through C#
Posted by Praveen Kumar on February 11, 2008
try {
var pageTracker = _gat._getTracker(“UA-7968286-1″);
pageTracker._trackPageview();
} catch(err) {}
protected void Button1_Click(object sender, EventArgs e)
{
try {
//XmlDataDocument sourceXML = new XmlDataDocument();
string xmlFile = Server.MapPath(“DVDlist.xml”);
//create a XML file is not exist
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(xmlFile, null);
//starts a new document
writer.WriteStartDocument();
//write comments
writer.WriteComment(“Commentss: XmlWriter Test Program”);
writer.Formatting = Formatting.Indented;
writer.WriteStartElement(“DVDlist”);
writer.WriteStartElement(“DVD”);
writer.WriteAttributeString(“ID”, “1″);
//write some simple elements
writer.WriteElementString(“Title”, “Tere Naam”);
writer.WriteStartElement(“Starring”);
writer.WriteElementString(“Actor”, “Salman Khan”);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.Close();
} catch (Exception e1) { Page.Response.Write(e1); }
}

preethi said
Hi
Praveen,
Your artical is nice,but in future the xml file may be change(in this example your hardcoding the file),so i want the code that is nutral to any xml file.
Thanks
Preethi.
praveensunsetpoint said
Hi Preethi,
a very good morning,
I appreciate ur comments but as u said “Your artical is nice,but in future the xml file may be change”
yeah then i have already described in another article named Read,Write XML with .Net where i am writing the “try.xml” through database dynamically in this i am reading and writing xml by two way statically and dynamically. Hope so now u got ur answer. Thanks for your time and cosideration. have a nice day
cheers,
Praveen
ashoktech said
hi ,
i would like generate an xml file in the following format.
to get values for my google maps
ashoktech said
hi ,
i would like generate an xml file in the following format.
to get values for my google maps
praveensunsetpoint said
Hi Ashok, as u asked “you want to generate xml file in the following format to get values for your google maps” but i did not get your xml format. could you please send me the format
Nithya said
hi praveen,
i want to insert entries dynamically..
plz help..
praveensunsetpoint said
Hi Nithya, you can insert entries dynamically, you just go through my article named “Read,Write XML with .Net” where i describes read/write xml from database/to database.
praveensunsetpoint said
Nithya said
praveen, i have opened the form in microsoft visual studio, so, how can i link webform and xml file usinf c# coding
Praveen said
Hi Nithya if you are using Visual studio 2005, you need to add an item xml file just go to website menu tab and add new item as an xml file. there is no need to link webform and xml file.
Nithya said
praveen,
i have added a webform with firelds like username and password, if iam new to tat page i should click “newuser” link and i want to enter my details in second form.
i have create the second form also , now wen i give the details and click save button, my details should be added in xml file.
and when iam enter the form by giving the username and password in the first page its, should match with the details in xml file and i should get into the nextform how can i do….
i don’t know where the details are saved and how it is retrived…
i tried ur coding …but, i can’t understand the process..
Praveen said
Hi Nithya
string xmlFile = Server.MapPath(”DVDlist.xml”);
//create a XML file is not exist
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(xmlFile, null);
//starts a new document
writer.WriteStartDocument();
//write comments
writer.WriteComment(”Commentss: XmlWriter Test Program”);
writer.Formatting = Formatting.Indented;
writer.WriteStartElement(“DVDlist”);
writer.WriteStartElement(“DVD”);
writer.WriteAttributeString(“ID”, TextBox1.Text);
please see the bold text where u can store the value of the ID attribute and xml file will be created automatically where your project directory resides find out where you are saved your project. and i have already described how you can read xml file to dataset. still if you have doubt ask me i’ll try to send you code first try it. best of luck
Nithya said
hey praveen , i have doubt in last line wat u mean by ID and Textbox, bcoz error is coming for textbox
Praveen said
<DVD ID=“Praveen”>Tere NaamSalman Khan
it will generate xml file dynamically and if u’ll give Praveen in TextBox which u added in aspx page, will give the value for ID
Aqeel said
could you post the output formate of the xml file
praveensunsetpoint said
Hi Aqeel as i have shown at top most
Tere Naam
Salman Khan
ashutosh said
i want to develope a live broadcast program in asp.net with c# by using webcam, pls give me solution on my mail jashutosh.software@gmail.com
jeeva said
hi praveen nice piece but i couldnt understand ur 12th post.
i m using asp.net and i want to save values to xml file which is dynamically created.creation og xml file is done but can u say hw can i set/save values(text of textbox of aspx page) to xml file.i m using c#.
plz help.
Praveen said
Hi Jeeva..did you try
writer.WriteAttributeString(”ID”, TextBox1.Text);
jeeva said
thnx for reply.
lets go through my code:
TextBox _text1 = new TextBox();
_text1.ID = “name”;
_text1.Enabled = true;
Button _btn = new Button();
_btn.ID=”but”;
_btn.Text=”save”;
_btn.Click += new EventHandler(testXml);
form1.Controls.Add(_btn);
form1.Controls.Add(_text1);
}
}
catch {}
}
public void testXml(object sender, EventArgs e)
{
string text = Request["name"];
//string _ProjectXml = Server.MapPath(“~/Projects/hy/hy.xml”);
XmlTextWriter writer = new XmlTextWriter((“D:/test.xml”), null);
writer.WriteStartDocument();
//write comments
writer.WriteComment(“Commentss: XmlWriter Test Program”);
writer.Formatting = Formatting.Indented;
writer.WriteStartElement(“DVDlist”);
writer.WriteStartElement(“DVD”);
writer.WriteAttributeString(“ID”, text);
}
have to append or ??
its not working but debugging shows the value of text box at text.
amod said
i have a xml file , now I want to add nodes in between , how can I do that. Can you pls give some sample code if possible .
praveensunsetpoint said
Hi Amod, you can add node by writing attributes in between..
please send me your xml file on praveen.sunsetpoint@gmail.com
jeeva said
hi praveen.
i have created an xml file.now i want to add tags using different function.
eg:
name,address tags will be created by alpha function.
roll,contact tags will be using another function say numeric.
how can i do it and save to the same file.
thanx in advance.
Praveen said
Sorry Jeeva i could not get..could you please be more specific to your problem yeah somehow i got you..send me your code
jeeva said
thanx.
i have xml file(its blank nothing is written).now i would like to write to that file.i am using C#.the file should look like as
but writing this type of file i have to use different function.for name tag function1,for address tag function2 and so on.and this should be saved at specified location(where the xml file is).i think its more clear now.
i m trying this n loading path to xml file for each function.any better idea.
Praveen said
Hi Jeeva
i have never done but thanks for giving me new idea
but this link may help you
Please check your mail
and do tell me it works?
jeeva said
sorry i cant use gmail at this time.can u send for me the link here.
Praveen said
when i am writing any link the message discarded.could you please give another gmail or send me your number so i will send..
jeeva said
u gotta mail.
u can send me the link at same address.
i will folow later
jeeva said
anyone know how to get folder name created using “directory.createDirectory” in C#.
i want to check existing folderName while creating new one to prevent override.folder name is given by user and if that name already exist there(at some location) then it will alert or shoiw msgBox asking to change folder name.
praveensunsetpoint said
Hi JeevaI think you can find out buy using if(!Directory.Exists(folderPath))
jeeva said
thanks its working.m going to replace my code which is as:
DirectoryInfo dir = new DirectoryInfo(folderPath);
FileSystemInfo[] checkProjName = dir.GetDirectories(ProjectName);
if (checkProjName.Length != 0)
{alert project name exist}
it may be useful for others.
Praveen said
Hi Jeeva, thank you so much by thinking that it may help to others..and if you get any new concept please do send me your articles or experience. i will paste your code in my blog and its aim to reach to each and every perosn.
asma said
how can i nsert data in existing XML file using c#..e.g i c raeted a an xml file share.aml and stored it in NewFolder in project..
Praveen said
Hi Asma, you can use XML path navigator
XmlDocument document = new XmlDocument();
document.Load(“contosoBooks.xml”);
XPathNavigator navigator = document.CreateNavigator();
navigator.MoveToChild(“bookstore”, “http://www.contoso.com/books”);
navigator.MoveToChild(“book”, “http://www.contoso.com/books”);
navigator.MoveToChild(“price”, “http://www.contoso.com/books”);
navigator.InsertBefore(“100″);
navigator.MoveToParent();
Console.WriteLine(navigator.OuterXml);
murad said
******Inserting Data to an XML Document******
Praveen….read this article…easy and gud one to understand….
The XmlNode and the XmlDocument classes can be used to insert XML data to an existing document or to a new document.
Adding namspace Reference
Since Xml classes are defined in the System.XML namespace, so first thing you need to do is to Add the System.XML reference to the project.
using System.Xml;
Loading XML to Document
LoadXml method of XmlDocument can be used to load XML data to a document or to load an existing XML document..
// Load XML data to a document
XmlDocument doc = new XmlDocument();
doc.LoadXml(“” +” Old Data” + “”);
Inserting XML Data
The below code inserts XML data to the file and saves file as InsertedDoc.xml.
Souce Code:
try
{
XmlNode currNode;
XmlDocument doc = new XmlDocument();
doc.LoadXml(“”+” Old Data” +”");
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml=”"+”Inserted Data”+”";
// insert the availability node into the document
currNode = doc.DocumentElement.FirstChild;
currNode.InsertAfter(docFrag, currNode.LastChild);
//save the output to a file
doc.Save(“InsertedDoc.xml”);
}
catch (Exception e)
{
Console.WriteLine (“Exception: {0}”, e.ToString());
}
output of the code looks like this -
Old Data
Inserted Data
murad.abbas@gmail.com
murad said
do let me know guyz if u want any thing else….
praveensunsetpoint said
Hi Murad , nice explanation. if you wish to post any articles or code please do post.
Thank you so much
murad said
what kind of article do u want me to post,,,,,
Praveen said
Any kind of article or code which could help developer. Thank you Muraad for showing your interest in good deed.
murad said
am trying to post some code here…it is saying discarded
Praveen said
sorry how you are posting by comment or some other way. ok you kindly please send me mail.
Thank you Murad
Regard Praveen
Nish said
Hi
I was wondering if you could help me. I have built a simple form using c# windows form. I wanted to save the data from the form into an xml file by clicking on “done”. How can i do this?
Thank you
Pradeep said
Hi praveen,
I have added a webform with fields username and password, if iam new to dat page i should click “Register” link and i want to enter my details in second form.i have the second form also , now wen i give the details and click “Create” button, my details should be added in xml file.and when i enter the form by giving the username and password in the first page it, should match with the details in xml file and i should be redirected into the nextform.Iam able to store values in Xml values.
How to validate the user names and passwords in the login form(i.e 1st form) from xml file where i have the details.
Praveen said
Hi Pradeep, if you are able write your registration details into xml file in same fashion you may read xml file and may validate login details. could you please what are the steps you applied so far or are you getting error. in category ‘xml’ i wrote one code to read xml file.please read that.. first read the xml file. Thank you.
srinivas said
Hi Praveen,
I need to create and store xml documents(Clinical Document Architecture CDA format) using the available transcription information. CDA format means its just like xml file format. These are the links to study about what is CDA? http://www.alschulerassociates.com/cda/?topic=quick-start-guides
http://www.hl7.org/documentcenter/public/faq/cda.cfm
If you have any idea regarding this CDA format and how to implement, Please help me.
Thanks in advance
praveensunsetpoint said
Hi Srinivas,
I visited your given link and every thing is well described.
I do not know where you are facing problem? could you please be more specific your problem i mean how far you have tried and where exactly you are stacked.so let others people also come up with new idea.
Thanks
srinivas said
Thanks for giving quick reply Praveen. I am not that much good in xml. I tried with writing code for generating the xml. I declared a class and properties and pass the values(using properties) to xml thru serialization.But I don’t know how to convert xml document to text document format with values. Please help me in this how to implement this CDA4CDT format.
Thanks in advance….
srinivas said
Praveen, I forgot to tell you that I am trying to implement this in C#.
Thanks
srinivas said
Hi Praveen,
I generated xml file with some missing xml root element tags. How do I add the root elements for the existing child nodes in C#. Please help me out.
Thanks
Nick said
Hi Praveen,
I am dynamically creating an xml file with values being entered by the user on a web form. I need to save the same xml file at a different location on the server but with a different filename ( original file name + todays date).
How should I go about it???
Thanks
praveensunsetpoint said
you can use XML DOM to save it on your server.
The following example shows how to use ASP to save an XML file on the server:
<%
text=”"
text=text & “Nick”
text=text & “Praveen”
text=text & “Hi”
set xmlDoc=Server.CreateObject(“Microsoft.XMLDOM”)
xmlDoc.async=”false”
xmlDoc.loadXML(text)
xmlDoc.Save(“email.xml”)
%>
here you need to create different obj to save the same file on different server. you may save with date too by using today date function. i might be wrong but this is idea which i could think.
Sridevi said
Hi Praveen,
I am trying to create a xmldocument and adding a new node to it as
XmlNode node=xmldoc.documentElement();
And then adding xmlelements to and getting the values from element.innertext=entitytype.empid.tostring();.
now while i am tring to save the xmldocument, its giving an error of xmldocument does not have a root element.
praveensunsetpoint said
Hi Sridevi, you are missing a root node
Please follow this.
// Get the root node so we can explore its children
XmlElement nodRoot = docXMLFile.DocumentElement;
// Store all the values of the elements in a string
string allMyChildren = nodRoot.InnerText;
// Locate the new make among the values of the elements
int indexLookForNewMake = allMyChildren.IndexOf(strNewMake);
hems said
hi i want to modify the values of some xml tags through C#, can you help in that ?
praveensunsetpoint said
Hi Hems, please
Follow these steps:
1. Load the XML Doc
2. Select the nodes you want to modify
3. Loop through the selected nodes and modify the element values
even if you see the reply of my last comments there you would have got some idea.
for eg
foreach (XmlNode node in doc.SelectNodes(“//price”))
{
node.InnerText = (XmlConvert.ToDouble(node.InnerText) * 1.2).ToString();
}
swati said
Hi…
I want to write the xml through database & i am having my database on mYSQl. Can you please help me out.
Thanks…
Swati
Praveen Kumar said
Hi Swati, please visit this link
http://praveensunsetpoint.wordpress.com/category/xml/
Kushal said
Hi,
I have a xml file that i have read with the help of xmltextreader from the machine in my C# winform application.Now i want to pass this file’s data to webservice.How can i do that?
Thanks
Kushal
Praveen Kumar said
Hi Kushal,
passing xml file’s data to web services depends on many issues.
following links may help you
XML’s data to webservices
XML’s data to webservices
Belal said
I have a question:
I want to delete a xml Element using Indexing number not by name.
Praveen Kumar said
Hi Belal
There are various options
you can use following methods
public virtual XmlNode RemoveAttributeAt(int i); It return the boolean value
Using the XmlElement.RemoveAt() method to delete an attribute can be uncertain because you would not know whether there is an attribute at the specified position. An alternative is to specify the name of the attribute you want to delete. To support this, the XmlElement class is equipped with the RemoveAttribute() method, which is overloaded with two versions. One of the versions of this method uses the following syntax:
public virtual void RemoveAttribute(string name);
This method expects as argument the name of the attribute to remove.
Another technique you can use consists of defining an XmlAttribute object and submitting to its XmlElement parent to delete. To do this, you can call the RemoveAttributeNode() method of the XmlElement object. Its syntax is:
public virtual XmlAttribute RemoveAttributeNode(XmlAttribute oldAttr);
When calling this method, pass the attribute object as argument. If the attribute exists, it would be removed and the method would return the deleted attribute. If the attribute doesn’t exist, nothing would happen.
To know more about the XML element. i may refer you to go through given link
XML.Net
gauri said
Hi
Praveen,
i want to write some information in xml file which is present in the window form by clicking a button which is present in window form in c#
gauri said
Hi
Praveen,
i want to validate window form in c# . form fields are name of filter, sourcefilepath.i want if name of filter all ready exist in database (an xml file )some error msg will be display and path will enter by browse button.
Praveen Kumar said
Hi Gauri,
Thats good question to validate the xml while writing.
Before going to post on our blog we would like to give you some concept to validate and assure that will help you.
The XMLReader class can enforce validation using a document type definition (DTD) or XML Schema definition language (XSD) schema.
Settings on the XMLReaderSettings object used by the (Create )method determine what type of data validation
XMLReaderSettings class have so many property for instance ValidationType, ValidationEventHandler, ValidationFlag, XMLResolver .
Thanks
Umaid said
Hi Praveen,
I am ew to xml scripting. Actually I am testing your above code in Windows application but it is showing me some errors, so can u please help.
I am enclosing my code as:
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;
using Microsoft.SqlServer;
namespace XMLCheck1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
TextBox _text1 = new TextBox();
//_text1.ID = “name”;
_text1.Enabled = true;
//Form1.Con.Add(_text1);
}
catch(Exception err) {
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//string text = Request["name"];
//XmlDataDocument sourceXML = new XmlDataDocument();
string xmlFile = Server.MapPath(“DVDlist1.xml”);
//create a XML file is not exist
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(xmlFile, null);
//starts a new document
writer.WriteStartDocument();
//write comments
writer.WriteComment(“Commentss: XmlWriter Test Program”);
writer.Formatting = System.Xml.Formatting.Indented;
writer.WriteStartElement(“DVDlist”);
writer.WriteStartElement(“DVD”);
writer.WriteAttributeString(“ID”, “textBox1.Text”);
//write some simple elements
writer.WriteElementString(“Title”, “Umaid Saleem”);
writer.WriteStartElement(“Starring”);
writer.WriteElementString(“Actor”, “Rock Star”);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.Close();
} catch (Exception e1)
{
Form1.Response.Write(e1);
}
}
It is show error at Server.MapPath(“Filename.xml”);
as the name server doesn’t exist in current context
My Form doesn’t contain a definition for response as
Form1.Response.Write(e1);