Rickard
Rickard

Reputation: 419

Read XML to dictionary

I know this question have been asked multiple times, but I have not manage to solve my problem despite trying several suggestions from other similar questions.

Now I ask instead, in hope to get an answer.

I have this XMl file:

<?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>

I need FullCommand and TimeStamp to be added to my dictionary

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

How do I:
1. Add the FullCommand and TimeStamp to the dictionary?
2. Convert the TimeStamp string into a proper DateTime?

Upvotes: 0

Views: 851

Answers (1)

Jaanus Varus
Jaanus Varus

Reputation: 3563

  1. Add the FullCommand and TimeStamp to the dictionary?
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. Convert the TimeStamp string into a proper DateTime
DateTime.Parse(xCommand.Element("TimeStamp").Value, CultureInfo.CurrentCulture)

Parsing to DateTime is a culture specific operation. Make sure you use the correct culture in case CultureInfo.CurrentCulture isn't viable.

Upvotes: 1

Related Questions