У меня есть этот код, чтобы забрать продукты и продовольственные товары из XML Att сначала я сохранил имя каждого 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 becuse _foodplace is not restuarant, как прийти arround this
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
}
}
Просто установите для свойства PreserveWhitespace
XMLDocument
значение false
перед загрузкой xml.
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = false;
doc.Load("your.xml");
Чтобы удалить пробелы и, возможно, рассмотреть чувствительность к регистру:
where String.Equals(_foodplaces.Value.Trim(), restaurant, StringComparison.OrdinalIgnoreCase)