该文档已有一个'DocumentElement'节点

时间:2011-06-07 08:52:14

标签: c# .net xml

我在文件末尾添加了一个新节点,但是我收到了写错误:

  

此文档已有“DocumentElement”节点。

我的代码:

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);

我的XML文件:

<?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>

1 个答案:

答案 0 :(得分:46)

你应该使用

XmlNode refElem = doc.DocumentElement.LastChild;

doc.DocumentElement.InsertAfter(entryElement, refElem);

修改

您也可以使用

doc.DocumentElement.AppendChild(entryElement);

在这种情况下,不需要refElem