2014-09-06 72 views
0

我基本上試圖做的是檢查在我的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!"; 
       } 
      } 

     } 

希望我解釋的不夠好,謝謝你們。

回答

0

您可以使用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!"; 
} 
+0

這工作完美。 – Spamsational 2014-09-06 03:21:11

0

財產知道下拉列表中選擇的值是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查詢過濾器中使用wherelet關鍵字:

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

1

用以下內容替換您的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 

}