检查在DropDownList中选择了什么值,并根据XML值检查它
问题描述:
我基本上试图做的是检查在我的dropDownList1中选择的值是否在我的XML文档中,如果是这样,则打印出它是胖内容。否则,我会返回字符串“对不起,我们找不到你的食物!”。现在,我只得到其他场景。任何帮助将是非常美妙的检查在DropDownList中选择了什么值,并根据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表达式来获取子节点<Name>
等于选择的食物有<Food>
节点,然后拿到<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!";
}
答
财产知道下拉列表中选择的值是SelectedValue
这样的:
DropDownList1.SelectedValue == foodName
我不明白你的第二个循环的需要,因为如果该项目被选中它甚至不核实。
另外,您可以使用LINQ来获取食物项的列表在XML中做这样的事情:
XDocument doc=XDocument.Load(Server.MapPath("the xml address"));
var items = (from item in doc.Root.Elements("Web_Service/Food")
select new {
name=c.Element("Name"),
};
然后,你可以从不同阵列的功能中获益,如:
Array.Exists(items, DropDownList1.SelectedValue)
或将其尽可能在您的LINQ查询过滤器中使用where
和let
关键字:
var items = (from item in doc.Root.Elements("Web_Service/Food")
let name = c.Element("Name")
where DropDownList1.SelectedValue == name
select new {
name=name,
};
+0
好的,非常感谢Dalorzo,我会给它一个去。 – Spamsational 2014-09-06 03:03:50
答
用以下内容替换您的foreach循环:
string nodeSelect = String.Format("Web_Service/Food/Name[@Value='{0}']",foodName);
XmlNodeList nodes = xDoc.SelectNodes(nodeSelect);
if (nodes.Count == 0)
{
TextBox2.Text = "sorry we could not find your food!";
}
else
{
//print the value fat value of that particular foodName
// address is ("Web_Service/Food/Fat
}
这工作完美。 – Spamsational 2014-09-06 03:21:11