Reputation: 933
I have an xml file that looks like this
<step>
<id>3</id>
<backid>1</backid>
<question>Are you having a good day</question>
<yesid>4</yesid>
<noid>5</noid>
</step>
It's set up to be an application that asks the user yes and no questions to assist in guiding the user through a complicated business process. The yesid and noid are the id numbers of the next step of the process. In the past (and in other languages) I would have loaded the info from the xml file into a multidimensional array and gone from there.
However I am attempting to use linq to xml in this application and I am wondering if there is a more efficient way of doing this than the xpath to array that I have been doing in the past
Upvotes: 4
Views: 3449
Reputation: 217411
I would create a class that represents a step, read the XML file into it using LINQ-to-XML, and then create a dictionary of steps for easy lookup:
var doc = XDocument.Load("xmlfile1.xml");
var steps = from step in doc.Root.Elements("step")
select new Step
{
Id = (int)step.Element("id"),
BackId = (int)step.Element("backid"),
Question = (string)step.Element("question"),
YesId = (int)step.Element("yesid"),
NoId = (int)step.Element("noid"),
};
var dict = steps.ToDictionary(step => step.Id);
var currentStep = dict[3];
while (true)
{
switch (Ask(currentStep.Question))
{
case Yes: currentStep = dict[currentStep.YesId]; break;
case No: currentStep = dict[currentStep.NoId]; break;
case Back: currentStep = dict[currentStep.BackId]; break;
default: return;
}
}
(Assuming the file contains several <step> elements under a common root.)
Upvotes: 6