我有这个代码从XML中获取食物和食物 首先,我已将每个restuarnt的名称存储在字符串列表中 我想选择列表中的这家餐馆的食物
foreach(var restaurant in restaurants)
{
List<foodplace> foodPlaces = (from _foodplaces in xmlDocument.Element("foodplaces").Elements("foodplace")
where _foodplaces.Value == restaurant
select new foodplace
{
day = (from day in _foodplaces.Elements(thisDay)
let list = day.Elements("food").Take(3).ToList()
select new DayOfWeek
{
food1 = (list.Count > 0 ? list[0].Value : string.Empty),
food2 = (list.Count > 1 ? list[1].Value : string.Empty),
food3 = (list.Count > 2 ? list[2].Value : string.Empty)
}).FirstOrDefault()
}).ToList();
问题是_foodplaces从xmldoxument返回看起来像这个
的值 \n\n\n\t the litle inddian \t\n\n\n
和restuarant值是一个字符串看起来像这个“litle indian”
所以linq语句返回null因为_foodplace不是restuarant 如何来到这个
答案 0 :(得分:0)
删除空格并考虑区分大小写:
where String.Equals(_foodplaces.Value.Trim(), restaurant, StringComparison.OrdinalIgnoreCase)
答案 1 :(得分:0)
string nameToSearch = "Restaurant12";
string xml = File.ReadAllText(<<pathtoxml>>, Encoding.Default);
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
//this depends on your xml structure: i assumed that the attribute of the restaurant is name
XmlNode node = doc.selectSingleNode("foodplaces/foodplace[@name = '"+nameToSearch +"']");
if(node != null){
foreach(XmlNode foodNode in node.selectNodes("food")){
//Do something with the foodnode
//e.g. foodNode.SelectsingleNode("Price").InnerText
}
}
答案 2 :(得分:0)
在加载xml之前,只需将PreserveWhitespace
的{{1}}属性设置为XMLDocument
。
false