I have four text boxes,
txtISBN.Text = string.Empty;
txtBookName.Text = string.Empty;
txtPublication.Text = string.Empty;
txtPublishYear.Text = string.Empty;
and File path
string sStartupPath = Application.StartupPath;
After filling all text boxes when you will click on Create XML Doc button, it will check if xml file is not exist than it will create an xml file and add element into it.
In this sample I'm not validating any data.
private void btnCreateXMLDoc_Click(object sender, EventArgs e)
{
AddBook(txtISBN.Text, txtBookName.Text, txtPublication.Text, txtPublishYear.Text);
}
private void AddBook(string ISBN, string Title, string Publisher, string PublishYear)
{
XmlElement booksElement = null ;
if (!File.Exists(sStartupPath + @"\Books.xml"))
{
if (booksElement == null)
{
booksElement = xmlDoc.CreateElement("Books");
xmlDoc.AppendChild(booksElement);
xmlDoc.Save(sStartupPath + @"\Books.xml");
}
}
else
{
xmlDoc.Load(sStartupPath + @"\Books.xml");
booksElement = xmlDoc.DocumentElement; //getting the root element name
}
XmlElement bookElement = xmlDoc.CreateElement("Book");
//Attributes are extra information added to a node element itself
XmlAttribute bookAttribute = xmlDoc.CreateAttribute("ISBN");
bookElement.SetAttributeNode(bookAttribute);
bookAttribute.Value = ISBN.Trim();
XmlElement titleElement = xmlDoc.CreateElement("Title");
titleElement.InnerText = Title.Trim();
bookElement.AppendChild(titleElement);
XmlElement releaseElement = xmlDoc.CreateElement("Release");
releaseElement.InnerText = PublishYear.Trim();
bookElement.AppendChild(releaseElement);
XmlElement publisherElement = xmlDoc.CreateElement("Publisher");
publisherElement.InnerText = Publisher.Trim();
bookElement.AppendChild(publisherElement);
booksElement.AppendChild(bookElement);
xmlDoc.Save(sStartupPath + @"\Books.xml");
}