从文件加载xml

时间:2016-10-15 07:02:37

标签: c# xml

一直在四处寻找我的问题的答案。我找到了将List转换为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文件中获取信息?

3 个答案:

答案 0 :(得分:1)

您可以使用XDocument.Load方法加载文档,然后使用LINQ to XML语法创建命令列表:

XDocument doc = XDocument.Load(file_path);
var commands = doc.Root.Elements("Commands").Select(e => 
                      new Command()
                      {
                        command = e.Attribute("command").Value, 
                        response = e.Attribute("response").Value,
                        author = e.Attribute("author").Value, 
                        count= int.Parse(e.Attribute("count").Value) 
                      }).ToList();

答案 1 :(得分:1)

当使用xml进行持久存储时,首先要定义POC类并用适当的属性装饰它们 - 比如

self.navigationController.navigationBar.hidden = NO;
[self.navigationItem setHidesBackButton:NO animated:YES];
self.navigationController.delegate = self;

然后反序列化很简单:

[XmlType("Command")]
public class CommandXml
{
    [XmlAttribute("command")]
    public string Command { get; set; }
    [XmlAttribute("response")]
    public string Response { get; set; }
    [XmlAttribute("author")]
    public string Author { get; set; }
    [XmlAttribute("count")]
    public int Count { get; set; }
}

[XmlRoot("Commands")]
public class CommandListXml : List<CommandXml>
{
}

答案 2 :(得分:1)

您可以使用以下代码:

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)
                     });
 }
相关问题