我有一个类似
的XML文档<recipes>
<ingredient value"1">APPLE</ingredient>
<ingredient value"2">BANANA</ingredient>
<ingredient value"3">APPLE ORANGE</ingredient>
<ingredient value"4">APPLE BANANA</ingredient>
<ingredient value"5">APPLE STRAWBERRY</ingredient>
<ingredient value"6">GRAPES</ingredient>
</recipes>
现在用户输入一些字符串,例如Apple Grapes Banana
。我按字母顺序对其进行排序,并尝试通过使用字符串操作递归消除最后一个单词来将其与其中一个值匹配。但我确信在Linq中有更有效的方法可以做到这一点。我希望查询返回XML <ingredient value"4">APPLE BANANA</ingredient>
中最接近的匹配。
string str = "APPLE BANANA GRAPES"; // user input arranged by ascending alphabet and capitalized
XDocument xdoc = XDocument.Load(above xml);// gets above xml
var h = xdoc.Root.Elements("ingredient").FirstOrDefault(u => u.Value == str);//recurse these steps
if (h == null)
{
str = str.Remove(str.LastIndexOf(" "));//recurse these steps
}
//check if str matches any value;
//if not remove last word from str and check again;
答案 0 :(得分:2)
我会尝试这样的事情:
string str = "APPLE BANANA GRAPES";
String[] criterias = str.Split(' ');
XDocument x = XDocument.Parse(yourXmlString);
var result =
x.Root.Elements()
// count # of matches for each element
.Select(e => new {e, num = criterias.Count(c => e.Value.Contains(c))})
// order by # of matches, then alphabetically
.OrderByDescending(r => r.num).ThenBy(r => r.e.Value)
// get a combination e: XElement, num: # of matches
.FirstOrDefault();
编辑:不确定匹配是否应该是搜索字符串的前缀。也许它更像这样:
var result =
x.Root.Elements()
// get prefixes
.Where(e => str.StartsWith(e.Value))
// count matchings
.Select(e=>new {e, num=e.Value.Split(' ').Length})
// get max matchings
.OrderByDescending(r => r.num).ThenBy(r => r.e.Value)
.FirstOrDefault();
答案 1 :(得分:1)
这里最接近匹配需要多个条件。
例如
var h = xdoc.Root.Elements("ingredient").FirstOrDefault(u => str.Contains(u.value))
是一个在示例中返回更近值的条件。
答案 2 :(得分:1)
我有一个简单的递归呈现
public string FindValueFromText(XDocument xdoc, string str)
{
while (str != "")
{
var h = xdoc.Root.Elements("ingredient").FirstOrDefault(u => u.Value == str);
if (h == null)
{
str = str.Remove(str.LastIndexOf(" "));
FindValueFromText(xdoc, str); //recursive
}
else
{
return h.Attribute("value").Value;
}
}
return "Not found value";
}
将这些行添加到您要在方法
上方调用的位置XDocument xDoc = XDocument.Load(xmlFilePath);
string value = FindValueFromText(xDoc, "APPLE BANANA GRAPES");