0) You can have only one root: you need an outer element like
books
for example.
1)
XmlDocument.DocumentElement[
^] will get the root.
2) Why mixing XDocument and XmlDocument like this?
I would use something like this (LinqPad demo):
XDocument addBook(string filename, string firstname, string lastname)
{
XDocument xml;
XElement books;
if (File.Exists(filename))
{
xml = XDocument.Load(filename);
books = xml.Root;
}
else
{
xml = new XDocument();
books = new XElement("books");
xml.Add(books);
}
books.Add(
new XElement("book",
new XElement("firstname", firstname),
new XElement("lastname", lastname))
);
xml.Save(filename);
return xml;
}
void Main()
{
Console.WriteLine(addBook(@"d:\temp\t.xml","John","Smith"));
}