使用 XmlWriter 附加到父标记内

Appending inside a parent tag using XmlWriter

我正在使用此代码写入 xml 文档。问题是每次我调用这段代码时,它都会覆盖以前编写的 Tags 元素。

但是我想在 Tags 元素中附加多个 Tag 元素。如何使用 XmlWriter?

制作此类集合
        using (XmlWriter writer = XmlWriter.Create(path))
        {
            writer.WriteStartElement("Tags");
            writer.WriteElementString("Tag", tagName);
            writer.WriteEndElement();
        }

我在网上找到了一些涉及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);
}

由于在每次函数调用时都会打开和保存文件,因此效率不是很高,但它可以满足您的要求。