一直在四处寻找我的问题的答案。我找到了一种将列表转换为 xml 文件的好方法,但我也想将其恢复为列表。
我当前的 xml 文件如下所示:
<Commands>
<Command command="!command1" response="response1" author="niccon500" count="1237"/>
<Command command="!command2" response="response2" author="niccon500" count="1337"/>
<Command command="!command3" response="response3" author="niccon500" count="1437"/>
</Commands>
生成方式:
var xml = new XElement("Commands", commands.Select(x =>
new XElement("Command",
new XAttribute("command", x.command),
new XAttribute("response", x.response),
new XAttribute("author", x.author),
new XAttribute("count", x.count))));
File.WriteAllText(file_path, xml.ToString());
那么,我如何从 xml 文件中取回信息呢?
最佳答案
您可以使用以下代码:
XDocument doc = XDocument.Load(@"myfile.xml");
将 XML 文件加载到 XDocument
中对象。
然后你可以使用.Descendants("Commands").Elements()
访问 <Commands>
中包含的所有元素元素并将它们添加到列表中:
List<Command> lstCommands = new List<Command>();
foreach(XElement elm in doc.Descendants("Commands").Elements())
{
lstCommands.Add(new Command
{
command = elm.Attribute("command").Value,
response = elm.Attribute("response").Value,
author = elm.Attribute("author").Value,
count = int.Parse(elm.Attribute("count").Value)
});
}
关于c# - 从文件中加载 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40056079/