我目前正在尝试在一个正在进行的小项目中实现搜索功能。有关该项目的一些背景知识,我有一个xml,可从其中导入一些存储在treeview中的数据。我的目标是能够提供一个字符串,并仅在树视图中显示包含该特定字符串的节点。
对于我的树形视图下面的xml来说是这样的
Breakfast
Belgian waffles
Strawberry Belgian Waffles
如果选择一个节点,则有一个带有一些文本框的分组框,其中包含每个项目的属性(价格,卡路里等)
[我希望我的功能能够搜索任何东西。即,如果我给出一个价格,如果我搜索华夫饼以显示所有华夫饼,则以该价格在树状视图中显示该项目。
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>
Two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>
Light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
</breakfast_menu>
我有一个递归函数,但是在第3(TreeNode t = treeNode.FirstNode)行,它弹出一个空引用异常。我的猜测是,当它碰到一个没有子节点的节点时,该异常弹出,但是我现在不知道如何处理它。
private void IterateRecursive(TreeNode treeNode)
{
TreeNode t = treeNode.FirstNode;
if (t!=null)
{
foreach (TreeNode tn in treeNode.Nodes)
{
IterateRecursive(tn);
}
}
if (!treeNode.Text.Contains(textBox_search_string.ToString()))
{
treeView1.Nodes.Remove(treeNode);
}
}
此外,如果我有其他方法可以使用此搜索功能,则可以提出建议。
public static void Search(string s)
{
bool node_add_decision = false;
int i = 0;
foreach (XmlNode p_node in xml_list)
{
i++;
node_add_decision = false;
if (p_node.Attributes.Count > 0)
{
foreach (XmlAttribute attr in p_node.Attributes)
{
if (attr.Name.Contains(s) || attr.Value.Contains(s))
{
node_add_decision = true;
}
}
if (!node_add_decision)
{
node_add_decision=search_c(p_node, s);
}
}
if (node_add_decision)
{
Add_search_list(p_node,i);
}
}
}
private static bool search_c(XmlNode xn, string s)
{
if (xn.HasChildNodes)
{
foreach (XmlNode chld in xn.ChildNodes)
{
for (int i = 0; i <= chld.ChildNodes.Count - 1; i++)
{
if(chld.ChildNodes[i].Value!=null)
{
if (chld.ChildNodes[i].Value.Contains(s))
return true;
}
if (chld.ChildNodes[i].Name.Contains(s))
{
return true;
}
else {
if (chld.ChildNodes[i].Attributes.Count > 0)
{
foreach (XmlAttribute attr in chld.ChildNodes[i].Attributes)
{
if (attr.Name.Contains(s) || attr.Value.Contains(s))
{
return true;
}
}
}
}
}
}
}
return false;
}
所以,我得到了名为Search的主要功能,对于列表中的每个节点,它将在所有属性中搜索所需的字符串。如果找到,则node_add_decision将设置为true,这意味着该节点包含该字符串,并且不再需要搜索它的子项。如果在当前节点中没有该字符串的踪迹,则该节点决定将为false,这意味着我们必须搜索它的子项。
search_c是通过子级搜索字符串的函数。对于每个子节点,我们都搜索该字符串,如果找到则返回true,否则返回false。
对于我来说,我必须显示不包含字符串的事件,但是它包含一个字符串。如果不是这种情况,则可以放弃search_c函数和代码的节点决定部分。