XML XPath Question
本文关键字:Question XPath XML | 更新日期: 2023-09-27 18:00:30
我的XML文件如下所示,我正在C Sharp代码中尝试让它只在组合框中填充基于所选课程名称的问题。因此,例如,如果他们在课程组合框中选择了XML编程,它将只在问题组合框中显示XML编程的问题。为了实现这一点,我的XPath需要什么样子?如有任何帮助,我们将不胜感激。
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>
我会使用LINQ到XML:
doc.Root.Elements()
.Where(c => c.Element("Name").Value == "Windows GUI")
.Elements("Questions")
但是,如果您真的想使用XPath,它看起来像这样:
/Courses/Course[Name = 'Windows GUI']/Questions
不过,在构造查询时要小心,因为必须对用户的字符串进行转义。
这将选择并在输出窗口中显示与所选课程相关的所有问题:
string xpath = string.Format("//Course[Name = '{0}']/Questions", comboBoxCourse.SelectedItem);
foreach (XmlNode node in loadDoc.SelectNodes(xpath))
Debug.WriteLine(node.InnerText);
要从这些结果加载另一个组合框,我会用以下内容替换您的整个方法:
string xpath = string.Format("//Course[Name = '{0}']/Questions", comboBoxCourse.SelectedItem);
foreach (XmlNode node in loadDoc.SelectNodes(xpath))
comboBoxQuestions.Items.Add(xml.InnerText);
使用此XPath表达式:
/*/*[Name = 'XML Programming']/Questions
这将选择任何Questions
元素,该元素是顶部元素的子元素,并且具有名为Name
的子元素(其字符串值为'XML Programming'
)