xml文档中的findnext()方法

时间:2013-03-18 19:48:28

标签: c# xml find

关于xml文档的另外一个问题。所以,我想通过消息体(文本)找到消息,我写了find()方法:

public void find(string searchText)
{
    XmlNodeList smss = xmlDoc.SelectNodes("//sms");
    searchText = txtFind.Text;

    foreach (XmlNode sms in smss)
    {
        if (sms.Attributes["body"].InnerText.Contains(searchText))
        {
            txtName.Text = sms.Attributes["body"].InnerText +
                           sms.Attributes["time"].Value;
            break;
        }
    }
}

此方法查找包含搜索字符串的第一条消息,并将其写入txtName文本框。现在,我想找到包含相同字符串的下一条消息并将其添加到txtname文本框,换句话说我想编写findNext()方法。我无法弄明白该怎么做。

2 个答案:

答案 0 :(得分:1)

您可以使用for循环并存储计数器的状态,然后从XMLNodeList跳转计数器元素并从那里再次开始搜索,例如:

//Assumes i is declared somewhere else 
for (i ; i < smss.Count; i++)
{
    if (smss[i].Attributes["body"].InnerText.Contains(searchText))
    {
        txtName.Text = smss[i].Attributes["body"].InnerText +
                       smss[i].Attributes["time"].Value;
        break;
    }
}

答案 1 :(得分:0)

我不确定你是否正在寻找这样的东西,但希望下面的例子可以帮助你

Private Sub CommandButton1_Click()
If OptionButton1 Then
Dim MyValue, MyFindNext
    [A1].Select
    MyValue = TextBox1.Value

    On Error GoTo err_Trap
    Cells.Find(What:=MyValue, After:=ActiveCell, LookIn:=xlValues, LookAt:= _
        xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Activate

    MyFindNext = vbYes
    Do Until MyFindNext <> vbYes
    MyFindNext = MsgBox("Would you like to find the next instance of " & MyValue & "?", _
        vbYesNo, "Find Next")
        If MyFindNext = vbNo Then
        Unload UserForm1
        Exit Sub
        End If
    Cells.FindNext(After:=ActiveCell).Activate
    Loop
    On Error GoTo 0
    Exit Sub
End If

If OptionButton2 Then
    [A1].Select
    MyValue = TextBox1

    On Error GoTo err_Trap
    Cells.Find(What:=MyValue, After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
        xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Activate

    MyFindNext = vbYes
    Do Until MyFindNext <> vbYes
    MyFindNext = MsgBox("Would you like to find the next instance of " & MyValue & "?", _
        vbYesNo, "Find Next")
        If MyFindNext = vbNo Then
        Unload UserForm1
        Exit Sub
        End If
    Cells.FindNext(After:=ActiveCell).Activate
    Loop
    On Error GoTo 0
    Exit Sub

err_Trap:
    If Err.Number = 91 Then
        MsgBox "Could not find " & MyValue & " anywhere on this sheet.", , "Search failed"
    Else
        MsgBox Err.Number & ": " & Err.Description
    End If
End If
End Sub

有关详细信息,请参阅此链接

http://www.knowexcel.com/view/931222-findnext-method-help-.html