2015-06-18 82 views
0

我知道这个问题已被多次询问,但我还没有设法解决我的问题,尽管尝试了几个其他类似问题的建议。阅读XML到字典

现在我请求,希望能得到答案。

我有这个XML文件:

<?xml version="1.0" encoding="utf-8"?> 
    <WebCommands> 
     <WebCommand> 
      <FullCommand>@ 05c9fe42-8d89-401d-a9a5-2d82af58e16f This is a test from WebCommands!</FullCommand> 
      <TimeStamp>18.06.2015 02:56:22</TimeStamp> 
     </WebCommand> 
    </WebCommands> 

我需要FullCommand和时间戳被添加到我的字典

Dictionary<DateTime, string> commands = new Dictionary<DateTime, string>(); 

如何:
1.添加FullCommand和时间戳到字典?
2.将TimeStamp字符串转换为适当的DateTime?

+0

[如何将XML转换为字典](http://stackoverflow.com/questions/13952425/how-to-convert-xml-to-dictionary) – Tim

回答

0
  1. 将FullCommand和TimeStamp添加到字典中?
var commands = new Dictionary<DateTime, string>(); 
XDocument xDoc = XDocument.Load("filename.xml");    
foreach (XElement xCommand in xDoc.Root.Elements()) 
{ 
    commands.Add(
     DateTime.Parse(xCommand.Element("TimeStamp").Value, CultureInfo.CurrentCulture), 
     xCommand.Element("FullCommand").Value); 
} 
  • 转换时间戳字符串转换成一个适当的日期时间
  • DateTime.Parse(xCommand.Element("TimeStamp").Value, CultureInfo.CurrentCulture) 
    

    解析到DateTime培养特定操作。确保你使用正确的文化,以防CultureInfo.CurrentCulture不可行。

    +0

    非常感谢您的帮助! – Rickard