2015-06-18 83 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