C# – This document already has a ‘ DocumentElement ‘ node

.netc++xml

I'm adding a new node at the end of a file, but I get a write error:

This document already has a 'DocumentElement' node.

My code:

XmlDocument doc = new XmlDocument();
doc.Load(directory);
XmlNode refElem = doc.LastChild; // Last node

foreach (MoneyEnter myList in list)
{
    XmlElement entryElement = doc.CreateElement("entry");
    entryElement.SetAttribute("type", myList.TypeAmount);

    XmlElement amountElement = doc.CreateElement("amount");
    amountElement.InnerText = Convert.ToString(myList.Amount);

    XmlElement dateElement = doc.CreateElement("date");
    dateElement.InnerText = Convert.ToString(myList.Date);

    XmlElement descriptionElement = doc.CreateElement("description");
    XmlCDataSection cdataDescription = doc.CreateCDataSection(myList.Description);
    descriptionElement.AppendChild(cdataDescription);

    XmlElement categoryElement = doc.CreateElement("category");
    categoryElement.InnerText = myList.Category;

    entryElement.AppendChild(amountElement);
    entryElement.AppendChild(dateElement);
    entryElement.AppendChild(descriptionElement);
    entryElement.AppendChild(categoryElement);
    doc.InsertAfter(entryElement, refElem); //add new node in end of file
}
doc.Save(directory);

My XML file:

<?xml version="1.0" encoding="utf-8" ?>
<entries>
    <entry type="debit">
        <amount>5</amount>
        <date>01.01.0001 0:00:00</date>
        <description>ffvfd</description>
        <category>fdvfvf</category>
    </entry>
    <entry type="debit">
        <amount>5</amount>
        <date>01.01.0001 0:00:00</date>
        <description>fvfv</description>
        <category>fvfdvfd</category>
    </entry>
    <entry type="debit">
        <amount>5</amount>
        <date>01.01.0001 0:00:00</date>
        <description>fv gfv</description>
        <category>dscdcd</category>
    </entry>
    <entry type="debit">
        <amount>5</amount>
        <date>01.01.0001 0:00:00</date>
        <description>vfvfv</description>
        <category>cfcfc</category>
    </entry>
    <entry type="debit">
        <amount>7</amount>
        <date>01.01.0001 0:00:00</date>
        <description>gfbvgv</description>
        <category>gfbgfb</category>
    </entry>
</entries>

Best Solution

You should use

XmlNode refElem = doc.DocumentElement.LastChild;

and

doc.DocumentElement.InsertAfter(entryElement, refElem);

EDIT

You may also use

doc.DocumentElement.AppendChild(entryElement);

In this case refElem is not needed.