You should use the XmlDocument class to load the whole file, modify it in memory and then write the contents back replacing the original file. Don't worry, it won't mess up your markup, and you can even ask it to preserve non-significant whitespace in the original document using the PreserveWhitespaceproperty (http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx).
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");
}