Question

I have a Student.xml and Lecturer.xml. When the user creates a new student he has to enter the Name, Surname and then select a lecturer from a list loaded from my Lecturer.xml.

How I get the list of lectures:

if (File.Exists("lecturer.xml"))

{

   XElement lecturelist = XElement.Load("lecturer.xml");
   Console.WriteLine("Select a lecturer:");

   foreach (var mainelement in lecturelist.Elements())
       {
           foreach (var subelement in mainelement.Elements())
               {
                   if (subelement.Name == "Name")
                       Console.Write("Lecturer: {0}", subelement.Value);

                   if (subelement.Name == "Surname")
                       Console.Write(", {0}", subelement.Value);

                   if (subelement.Name == "Specialisation")
                       Console.Write(" Subject: {0} \n", subelement.Value);
               }
       }

       Console.ReadLine();

}

else { Console.WriteLine("The lecturer.xml file is missing or corrupt...");

   Console.ReadLine();

}

Now this creates a list of lectures Example:

Lecturer: John, Kingsley Subject: Maths

Lecturer: Ben, Hur Subject: English

How can I change my code so it displays:

1 - Lecturer: John, Kingsley Subject: Maths

2 - Lecturer: Ben, Hur Subject: English

So that the user can type 1 or 2 to select a lecturer?

Was it helpful?

Solution

set the variable so that if they don't pick one it doesn't error out.

Int intLecturerNum = 1;

then pull in their answer from the console.

intLecturerNum = Convert.ToInt(Console.Readline());

been a while since I had to do this, and I was doing it with a Yes or No and there was a little bit more that I had to do with it so that I would get the right answer to my variable, but this is the general way that you pull in the variable.

XElement lecturelist = XElement.Load("lecturer.xml");
Console.WriteLine("Select a lecturer:");

String strProf;
Int i = 1;


foreach (var mainelement in lecturelist.Elements())
    {
        Console.Write(i.ToString() + " - ");
        foreach (var subelement in mainelement.Elements())
            {


                if (subelement.Name == "Name")
                {
                    Console.Write("Lecturer: {0}", subelement.Value);

                }
                if (subelement.Name == "Surname")
                    Console.Write(", {0}", subelement.Value);

                if (subelement.Name == "Specialisation")
                    Console.Write(" Subject: {0} \n", subelement.Value);

                i++;
            }
    }

\\ somewhere after this is where you read in the answer given by the user

you could Create a list and populate that list with Lecturers while you are printing them out.

or

you could create a class that will allow you to create Lecturer objects and give them a value.

or

...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top