gpt4 book ai didi

c# - 使用 XDocument 不规则写入 XML

转载 作者:太空宇宙 更新时间:2023-11-03 10:27:32 25 4
gpt4 key购买 nike

我一直致力于以 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;
}
}

关于c# - 使用 XDocument 不规则写入 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31214957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com