XML XPath Question

My XML file looks like the one below, I'm trying to use Sharp C code so that it only populates a combo box with questions based on the name of the selected course name. So, for example, if they choose XML programming in the course combobox field, only questions for XML programming will be displayed in the combobox question. What will be my XPath to do this? Any help would be appreciated.

if (comboBoxCourse.SelectedItem.ToString() == selectNode.InnerText ) { try { XmlNodeList loadQuestions = loadDoc.SelectNodes("//Course/Questions"); foreach (XmlNode xml in loadQuestions) { if (comboBoxCourse.SelectedItem.ToString() == selectNode.InnerText) comboBoxQuestions.Items.Add(xml.InnerText); else continue; } } catch (XmlException ex) { MessageBox.Show(ex.ToString()); } } 
 <?xml version="1.0" encoding="utf-8" ?> <Courses> <Course> <Name>Direct X Programming</Name> <Professor>Michael Feeney</Professor> <Questions>Are you a Ninja</Questions> <Questions>What version of Direct X do we use?</Questions> </Course> <Course> <Name>XML Programming</Name> <Professor>Michael Feeney</Professor> <Questions>Are you an XML Ninja?</Questions> <Questions>What does XML stand for?</Questions> </Course> <Course> <Name>Windows GUI</Name> <Professor>Leanne Wong</Professor> <Questions>What is a treeview?</Questions> <Questions>What is a database?</Questions> </Course> </Courses> 
+4
source share
3 answers

Instead, I would use LINQ to XML:

 doc.Root.Elements() .Where(c => c.Element("Name").Value == "Windows GUI") .Elements("Questions") 

But if you really want to use XPath, it will look something like this:

 /Courses/Course[Name = 'Windows GUI']/Questions 

Be careful when building a query because you need to do some string escaping from the user.

+2
source

This will display and display in the output window all the questions related to the selected course:

 string xpath = string.Format("//Course[Name = '{0}']/Questions", comboBoxCourse.SelectedItem); foreach (XmlNode node in loadDoc.SelectNodes(xpath)) Debug.WriteLine(node.InnerText); 

To load another combobox from these results, I would replace your entire method with the following:

 string xpath = string.Format("//Course[Name = '{0}']/Questions", comboBoxCourse.SelectedItem); foreach (XmlNode node in loadDoc.SelectNodes(xpath)) comboBoxQuestions.Items.Add(xml.InnerText); 
+1
source

Use this XPath expression :

 /*/*[Name = 'XML Programming']/Questions 

This selects any Questions element that is a child of any element that is a child of the top element and has a child element named Name whose string value is 'XML Programming'

+1
source

All Articles