I'm making a simple to-do list and want to store the tasks in an XML file. My XML file looks like this:
<Task>
<Title>Make a List</Title>
<Description>I should make a List!</Description>
<Done>false</Done>
</Task>
Every task is in the <Task>
tag which stores the title, description and if it's done.
When the form loads, I want to generate a checkbox for each task with
Text = <Title>
ToolTip = "<Description>"
Checked = <Done>
Right now my code looks like this:
void MainFormLoad(object sender, EventArgs e)
{
var doc = XDocument.Load(Application.StartupPath + "\\tasker.xml");
var Title = doc.Root.Descendants().Single(d => d.Name == "Title").Value;
var Description = doc.Root.Descendants().Single(d => d.Name == "Description").Value;
var Done = doc.Root.Descendants().Single(d => d.Name == "Done").Value;
MessageBox.Show(Title.ToString() + Environment.NewLine + Description.ToString() ); // Just for Testing
}
This works great, but only works for one task. How can I add checkboxes for more than one task?
Well, firstly you'd need multiple tasks in your XML file, e.g.
<Tasks>
<Task>
...
</Task>
<Task>
...
</Task>
</Tasks>
Then you could iterate over all the tasks like this:
var doc = XDocument.Load("...");
var tasks = doc.Root.Elements("Task")
.Select(x => new {
Title = (string) x.Element("Title"),
Description = (string) x.Element("Description"),
Done = (bool) x.Element("Done");
});
foreach (var task in tasks)
{
// Use task.Title etc
}
You don't have to use a separate local variable for that, but it looks simpler to me. You might want to create a named class for a task as well, rather than using the anonymous type that I've created here.
Note that an alternative to elements would be to use attributes for the data for each task.
See more on this question at Stackoverflow