请查看我的XML文件:
<?xml version="1.0" encoding="utf-8"?>
<!--XML Database.-->
<data>
<student>
<name>John E.</name>
<tests>
<test>
<lesson>Mathematics</lesson>
<grade>A</grade>
</test>
<test>
<lesson>Physics</lesson>
<grade>A+</grade>
</test>
</tests>
</student>
<!-- sidenote: jessica didn't attend the physics exam-->
<student>
<name>Jessica B</name>
<tests>
<test>
<lesson>Mathematics</lesson>
<grade>B</grade>
</test>
</tests>
</student>
</data>
我试图展示每个学生的测试。我的应用程序(TextBox1)中有1个文本框,我想输入&#34; John E。&#34;或者&#34; Jessica B。&#34;它会给我我们做过的测试。
已经添加了一个包含2个列的ListView:lesson,grade。
我尝试了很多方法,但还没找到一个有效的方法。编写这样的XML结构很容易,但无法完成阅读工作。感谢任何帮助。
请注意我目前正在使用此代码: http://forum.codecall.net/topic/69450-writing-and-reading-xml-files-vbnet-part-ii所以你可以根据这个做出答案,这样可以节省你的时间。
答案 0 :(得分:0)
这是您需要的代码:两个按钮(一个用于“搜索”,另一个用于清除文本框和列表视图字段)和一个文本框和列表视图。
设置listview列的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结构:节点和子节点。但总是一样的!必须有一种最简单的方法,但这是编程的好习惯。