如何在现有XML文件的末尾添加新节点?

时间:2011-06-05 16:36:21

标签: c# xml

如何在现有XML文件的末尾添加新节点?

我明白怎么做,但到底怎么样?

例如,我有以下XML文件,需要在文件末尾添加一个新节点“entry”:

<?xml version="1.0" encoding="utf-8" ?> 
- <entries>
- <entry type="debit">
<amount>100</amount> 
<date>11.11.2010</date> 
- <description>
- <![CDATA[ Описание записи]]> 
</description>
<category>Продукты</category> 
</entry>
- <entry type="credit">
<amount>50</amount> 
<date>11.11.2010</date> 
- <description>
- <![CDATA[ Описание записи]]> 
</description>
<category>Продукты</category> 
</entry>
- <entry type="debit">
<amount>100</amount> 
<date>11.11.2010</date> 
- <description>
- <![CDATA[ Описание записи]]> 
</description>
<category>Продукты</category> 
</entry>
</entries> 

2 个答案:

答案 0 :(得分:7)

最简单的方法是将XML加载到内存中,附加子节点,然后再次写出整个文档。例如:

XDocument doc = XDocument.Load("before.xml");
doc.Root.Add(new XElement("extra"));
doc.Save("after.xml");

如果这不完全是你所追求的,请澄清你的问题。

答案 1 :(得分:1)

XmlDocument doc = new XmlDocument();
doc.LoadXml("before.xml");
//XmlNode root = doc.DocumentElement;

//Create a new node.
XmlElement elem = doc.CreateElement("entry");
elem.InnerText="";
//Add the node to the document.
//root.AppendChild(elem);

//Console.WriteLine("Display the modified XML...");

doc.LastChild.AppendChild(elem);

doc.Save("before.xml");'
相关问题