C# 使用XmlWriter在父标记内追加
我使用这段代码来编写xml文档。问题是每次我调用此代码时,它都会覆盖以前编写的Tags元素 但是,我想在Tags元素中附加多个Tag元素。如何使用XmlWriter创建这样的集合C# 使用XmlWriter在父标记内追加,c#,.net,xml,asp.net-mvc-4,C#,.net,Xml,Asp.net Mvc 4,我使用这段代码来编写xml文档。问题是每次我调用此代码时,它都会覆盖以前编写的Tags元素 但是,我想在Tags元素中附加多个Tag元素。如何使用XmlWriter创建这样的集合 我在网上发现了几个涉及LINQ的解决方案,我不太擅长这些解决方案。所以我正在寻找没有它的东西?这可以通过Linq Xml通过以下方式完成: public void AddTagToXml(string path, string tag) { XDocument doc; // Load the exi
我在网上发现了几个涉及LINQ的解决方案,我不太擅长这些解决方案。所以我正在寻找没有它的东西?这可以通过Linq Xml通过以下方式完成:
public void AddTagToXml(string path, string tag)
{
XDocument doc;
// Load the existing file
if (File.Exists(path)) doc = XDocument.Load(path);
else
{
// Create a new file with the parent node
doc = new XDocument(new XElement("Tags"));
}
doc.Root.Add(new XElement("tag", tag));
doc.Save(path);
}
由于文件在每次函数调用时都会打开和保存,因此效率不高,但它满足了您的需求 不确定,但每次调用该代码段时似乎都在创建一个新的XmlWriter。您需要将其拆分为创建writer并附加document元素的函数和附加新子节点的函数。
public void AddTagToXml(string path, string tag)
{
XDocument doc;
// Load the existing file
if (File.Exists(path)) doc = XDocument.Load(path);
else
{
// Create a new file with the parent node
doc = new XDocument(new XElement("Tags"));
}
doc.Root.Add(new XElement("tag", tag));
doc.Save(path);
}