使用 XDocument 不规则写入 XML

Irregular writing to XML with XDocument

我一直致力于在 XML 中存储数据,但我使用了一个级别系统来允许用户访问某些数据而不是其他数据。但是这种情况发生在不同的周期并且数据被读取和写入是不规则的。这给了我以下错误:

Additional information: This operation would create an incorrectly structured document.

在:

doc.Add(new XElement(UserLevel, new XElement(CommandName.Remove(0, 1), CommandInfo)));

这是完整的函数:

private bool SetCommands(string CommandName, string CommandInfo, string UserLevel)
{
    if (GetCommand(CommandName) == "none")
    {
        XDocument doc = new XDocument();

        if (File.Exists(XmlFileLocation))
            doc = XDocument.Load(XmlFileLocation);

        doc.Add(new XElement(UserLevel, new XElement(CommandName.Remove(0, 1), CommandInfo)));
        doc.Save(XmlFileLocation);
        return true;
    }
    else
    {
        return false;
    }
}

我想要的是能够在相同的 UserLevel 下使用不同的 CommandNames 写入文件,然后保存不同的 CommandInfos。稍后我打算能够编辑CommandInfo,所以我必须覆盖已经写的东西。

我在寻找什么?

一个 XML 文档只能有一个根元素,而您似乎试图添加多个。只需创建一个顶级元素,比如 Users,然后添加 UserLevel 作为它的子元素。

像这样:

private bool SetCommands(string CommandName, string CommandInfo, string UserLevel)
{
    if (GetCommand(CommandName) == "none")
    {
        XDocument doc = new XDocument();

        if (File.Exists(XmlFileLocation))
            doc = XDocument.Load(XmlFileLocation);

        var users = doc.Root.Element("Users");
        if (users == null)
        {
            users = new XElement("Users");
            doc.Add(users);
        }

        users.Add(new XElement(UserLevel, new XElement(CommandName.Remove(0, 1), CommandInfo)));
        doc.Save(XmlFileLocation);
        return true;
    }
    else
    {
        return false;
    }
}