【问题标题】:Irregular writing to XML with XDocument使用 XDocument 不规则地写入 XML
【发布时间】:2015-09-21 18:38:09
【问题描述】:

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

附加信息:此操作将创建一个不正确的 结构化文档。

在:

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;
    }
}

我想要的是能够使用不同的 CommandNames 写入同一 UserLevel 下的文件,这些 CommandNames 然后持有不同的 CommandInfos。稍后我计划能够编辑 CommandInfo,因此我将不得不覆盖已写入的内容。

我在寻找什么?

【问题讨论】:

    标签: c# xml merge linq-to-xml


    【解决方案1】:

    一个 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;
        }
    }
    

    【讨论】:

    • 它工作,并感谢您的建议,但不断保存给出了同样的错误。但不在同一个地方。当它想要执行doc.save(XMLFileLocation); 时,它现在得到它。有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2018-01-05
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多