c# - 从文件中加载 xml

标签 c# xml

一直在四处寻找我的问题的答案。我找到了一种将列表转换为 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/

相关文章:

c# - 如何从另一个 .ascx 中的 .ascx 获取变量?

c# - 在 c# 中创建一个客户端来调用没有 wsdl 的 web 服务

java - 解析 xml 找不到架构文件

c# - XSD类生成嵌套表问题

python - 将 XML 解析为 Pandas DataFrame 为 CSV

java - 将字符串从 xml 响应转换为 pdf

c# - 如何在 C# 中从 json 模式创建默认的 json 对象

c# - 如何读取超过 65535 行的 Excel 2007 电子表格?

c# - 使 Contract.Assert 抛出异常而不是显示对话框

python - 元素树 : Can't build root tree when getting XML from webpage