I\'m planning to create a news item which uses xml as it\'s backend and the Display should be like:
Date: 08/Mar/2010
------------------------------
Title &
I was able to figure out the answer and was able to make my 1st trial with xml a success. I was trying to work with xml and C#. So I started on with a small thing:
- A windows form to accept Employee Department, name, and Emp No.
- On the press of "Submit" button the xml will be written, then all textbox will be cleared, and xml will be displayed to the user.
Here's the working code of button click.
private void button1_Click(object sender, EventArgs e)
{
string path = "employee.xml";
if (File.Exists(path))
{
// to append a new user having reset the textboxes
XDocument doc = XDocument.Load(path);
XElement xe = new XElement("user",
new XElement("department", textBox1.Text),
new XElement("name", textBox2.Text),
new XElement("empno", textBox3.Text)
);
doc.Root.Add(xe);
doc.Save(path);
}
else
{
new XDocument(
new XElement("users",
new XElement("user",
new XElement("department", textBox1.Text),
new XElement("name", textBox2.Text),
new XElement("empNo", textBox3.Text)
)
)
).Save(path);
}
textBox1.Text="";
textBox2.Text="";
textBox3.Text="";
MessageBox.Show("Data added successfully","Done!!",MessageBoxButtons.OK);
this.button1.Enabled=false;
f2=new Form2();
f2.FormClosed += Form2_FormClosed;
f2.Show();
}
Sadly I was not able to get any help from here(Stackoverflow) for editing the xml... so I decided to share the code with everybody here. Maybe this answer will help someone new like me.
This code could be modified with better skills and utilities, and if somebody has time & interest in helping a newbie then please do come forward.
Gud luck to all newbies here :)
There are a million ways to do this. The approach I'd take in the situation you described:
XDocument
or XmlWriter
to produce the XML.What I wouldn't do: Write a method in the form that pulls data out of the form controls and writes them to XML.
There are numerous ways of creating XML files in .NET. You could use object serialization , XmlWriter, XDocument, ...
Here's an example:
new XDocument(
new XElement("user",
new XElement("name", textBox1.Text),
new XElement("age", textBox2.Text),
new XElement("rollNo", textBox3.Text)
)
).Save("user.xml");
Could generate an XML file that looks like that:
<?xml version="1.0" encoding="utf-8"?>
<user>
<name>foo</name>
<age>20</age>
<rollNo>123</rollNo>
</user>