Xml to data structure

I have an xml file that looks like

<step> <id>3</id> <backid>1</backid> <question>Are you having a good day</question> <yesid>4</yesid> <noid>5</noid> </step> 

It is configured as an application that asks the user yes and no questions to help guide the user through a complex business process. The dydes and noid are the identification numbers of the next step in the process. In the past (and in other languages), I would load information from an xml file into a multidimensional array and leave there.

However, I am trying to use linq for xml in this application, and I am wondering if there is a more efficient way to do this than the xpath array that I did in the past.

+4
source share
1 answer

I would create a class that represents a step by reading the XML file in it using LINQ-to-XML, and then creating a step dictionary for easy searching:

 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.)

+6
source

All Articles