【问题标题】:Read XML to dictionary将 XML 读入字典
【发布时间】:2015-06-18 21:25:16
【问题描述】:

我知道这个问题已被多次问过,但尽管尝试了其他类似问题的若干建议,但我仍未能解决我的问题。

现在我转而问,希望得到答案。

我有这个 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 和 TimeStamp 添加到我的字典中

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

我该怎么做:
1. 将 FullCommand 和 TimeStamp 添加到字典中?
2.将TimeStamp字符串转换成合适的DateTime?

【问题讨论】:

标签: c# xml linq-to-xml


【解决方案1】:
  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);
}
  1. 将时间戳字符串转换为合适的日期时间
DateTime.Parse(xCommand.Element("TimeStamp").Value, CultureInfo.CurrentCulture)

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

【讨论】:

  • 非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 2010-09-25
相关资源
最近更新 更多