C# 从xml中选取元素

C# 从xml中选取元素,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,我有这个代码从XML中提取食物和食物位置 Att首先,我将每个RESTUART的名称存储在一个字符串列表中 我想挑选名单上这家餐馆提供的食物 foreach(var restaurant in restaurants) { List<foodplace> foodPlaces = (from _foodplaces in xmlDocument.Element("foodplaces").Elements("foodplace")

我有这个代码从XML中提取食物和食物位置 Att首先,我将每个RESTUART的名称存储在一个字符串列表中 我想挑选名单上这家餐馆提供的食物

 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();
restuarant值是一个字符串,看起来像“litle indian”

因此linq语句返回null,因为foodplace不是restarant
如何去掉这个

< P>来去除空格,或者考虑用例敏感性:

where String.Equals(_foodplaces.Value.Trim(), restaurant, StringComparison.OrdinalIgnoreCase)
string nameToSearch=“Restaurant12”;
字符串xml=File.ReadAllText(,Encoding.Default);
XmlDocument doc=新的XmlDocument();
doc.LoadXml(xml);
//这取决于xml结构:我假设餐厅的属性是name
XmlNode node=doc.selectSingleNode(“foodplaces/foodplace[@name='”+nameToSearch+“]”);
如果(节点!=null){
foreach(节点中的XmlNode foodNode.selectNodes(“food”)){
//用foodnode做点什么
//e、 g.foodNode.选择SingleNode(“价格”).InnerText
}
}

在加载xml之前,只需将
XMLDocument
PreserveWhitespace
属性设置为
false

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = false;
doc.Load("your.xml");
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
    }
}
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = false;
doc.Load("your.xml");