检查在DropDownList中选择的值,并将其与XML值进行比较
本文关键字:XML 比较 DropDownList 选择 检查 | 更新日期: 2023-09-27 18:20:55
我主要想做的是检查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!";
}
}
}
希望我解释得足够好,谢谢大家。
用以下内容替换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
}
您可以使用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,
};