這是你需要的代碼:兩個按鈕(一個用於「搜索」,另一個用於清晰的文本框和列表視圖字段)以及一個文本框和一個列表視圖。
的Form Load
其設置列表視圖列:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListView1.Columns.Add("Lesson", 100, HorizontalAlignment.Left)
ListView1.Columns.Add("Grade", 150, HorizontalAlignment.Left)
End Sub
併爲搜索按鈕單擊事件:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim isStudent As Boolean = False
Dim XmlDoc As XmlDocument = New XmlDocument()
Dim str(2) As String
Try
XmlDoc.Load("Put your XML file path here!")
Catch ex As Exception
MsgBox("XML Loading failled : " & vbCrLf & ex.Message & vbCrLf)
End Try
Dim element As XmlNodeList
Try
element = XmlDoc.DocumentElement.GetElementsByTagName("student")
For Each dataNode In element
//Go into data node
If dataNode.LocalName = "student" Then
For Each studentNode In dataNode.ChildNodes
//Loops the student childnodes
If studentNode.LocalName = "name" Then
If studentNode.InnerText.ToString.Trim.Equals(TextBox1.Text) Then
isStudent = True
Else
isStudent = False
End If
ElseIf studentNode.LocalName = "tests" And isStudent Then
For Each tests In studentNode.ChildNodes
//Loops tests childnodes...
If tests.LocalName = "test" Then
For Each test In tests.ChildNodes
//Loops test childnodes
If test.LocalName = "lesson" Then
str(0) = test.InnerText.ToString.Trim
ElseIf test.LocalName = "grade" Then
str(1) = test.InnerText.ToString.Trim
End If
Next
ListView1.Items.Add(New ListViewItem({str(0), str(1)}))
End If
Next
End If
Next
End If
Next
Catch ex As Exception
MsgBox("XML reading failed at element: " & vbCrLf & ex.Message & vbCrLf)
End Try
End Sub
清除按鈕只是讓你不斷地尋找新的學生:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox1.Text = ""
ListView1.Clear()
ListView1.Columns.Add("Lesson", 100, HorizontalAlignment.Left)
ListView1.Columns.Add("Grade", 150, HorizontalAlignment.Left)
End Sub
嘗試研究代碼並理解XML閱讀作品。看起來很難,但這種方式總是相同的,它取決於你的XML結構:節點和子節點。但總是一樣的!必須有一個最簡單的方法來做到這一點,但這是編程的好習慣。
顯示您嘗試閱讀XML的代碼。 – Tim
我建議使用LINQ to XML - 這很容易,IMO。 – Tim
我想運行For Each,使用特定名稱的學生,並顯示所有測試,您認爲使用LINQ可能嗎? – user3800799