[英]Load xml from file
一直在四處尋找我的問題的答案。 我找到了將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文件中獲取信息?
您可以使用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();
當使用xml進行持久存儲時,首先要定義POC類並用適當的屬性裝飾它們 - 比如
[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>
{
}
然后反序列化很簡單:
var txt = @"<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>";
CommandListXml commands;
using (var reader = new StringReader(txt))
{
var serializer = new XmlSerializer(typeof(CommandListXml));
commands = (CommandListXml)serializer.Deserialize(reader);
}
您可以使用以下代碼:
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)
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.