实际上,我要做的是检查在dropDownList1中选择的值是否在XML文档中,如果是,则打印出它的脂肪含量。否则,我返回字符串“对不起,我们找不到您的食物!”。就目前情况而言,我只会遇到其他情况。任何帮助都太棒了
我的代码如下:
XmlDocument xDoc = new XmlDocument();
xDoc.Load("the xml address");
// go through each food name (this works)
foreach (XmlNode name in xDoc.SelectNodes("Web_Service/Food/Name"))
{
//grab the string
string foodName = name.InnerText;
// what I'm tring to here is loop through the items in the dropdown list
// and check it against foodName
foreach (ListItem li in DropDownList1.Items)
{
if (li.Value == foodName)
{
// print the value fat value of that particular foodName
// address is ("Web_Service/Food/Fat")
}
else
{
TextBox2.Text = "sorry we could not find your food!";
}
}
}
希望我能解释得足够好,谢谢大家。
您可以使用XPath表达式获取<Food>
具有<Name>
等于所选食物的<Fat>
子节点的节点,然后获取该子节点。所有这些都在一个XPath表达式中,因此您无需手动循环遍历每个<Food>
节点即可完成此操作。例如 :
string foodName = DropDownList1.SelectedValue;
string xpath = String.Format("Web_Service/Food[Name='{0}']/Fat", foodName);
XmlNode fatNode = xDoc.SelectSingleNode(xpath);
if(fatNode != null)
{
TextBox2.Text = fatNode.InnerText;
}
else
{
TextBox2.Text = "sorry we could not find your food!";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句