gpt4 book ai didi

c# - 该文档已有 ' DocumentElement ' 节点

转载 作者:可可西里 更新时间:2023-11-01 03:03:56 24 4
gpt4 key购买 nike

我在文件末尾添加了一个新节点,但出现写入错误:

This document already has a 'DocumentElement' node.

我的代码:

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>

最佳答案

你应该使用

XmlNode refElem = doc.DocumentElement.LastChild;

doc.DocumentElement.InsertAfter(entryElement, refElem);

编辑

你也可以使用

doc.DocumentElement.AppendChild(entryElement);

在这种情况下,不需要 refElem

关于c# - 该文档已有 ' DocumentElement ' 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6262815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com