我对 VB 很陌生,对 XML 和 xpath 更是如此。我有一个列表视图框,它传递标识 xml 文件中的节点所需的变量(在下面的情况下,变量是 id 元素的文本值。
该变量选择一个节点,但我需要它的一些兄弟/子节点的内部文本。我知道如何制作 xmlnodelists 并编写它们的内部文本没问题,但我无法完成这项工作。这是我的 xml 示例(我没有编写 xml 文件,因此无法更改它):
<file>
<outcomes>
<outcome>
<id>CPK</id>
<id_text>description</outcome_text>
<indicators>
<indicator>
<p>the text i want to write to listbox</p>
</indicator>
<indicator>
<p>more text I want to write</p>
</indicator>
</indicators>
</outcome>
<outcome>
<outcome>
<id>CPK</id>
<id_text>description</id_text>
<indicators>
<indicator>
<p>the text i want to write to listbox</p>
</indicator>
<indicator>
<p>more text I want to write</p>
</indicator>
</indicators>
</outcome>
<outcome>
</outcomes>
</file>
所以假设传递的变量是“CPK”
这是我的代码:
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
'get variable to identify node
Dim id As String
Dim out As String
id = Me.outListView.SelectedItems(0).Text
out = Me.outListView.SelectedItems(0).SubItems(1).Text
IndForm.SelOutBox.Text = id & " " & out
'start xpath navigation
Dim document As XPathDocument = New XPathDocument("C:\Temp\" & sb & "_education_" & gr & ".XML")
Dim navigator As XPathNavigator = document.CreateNavigator()
'select the node with with variable, by text value
navigator.SelectSingleNode("/files/outcomes/goal_section/outcome/id[@text='" & id & "']")
'move to the needed node
navigator.MoveToNext() 'should be at /outcome/id_text
navigator.MoveToNext() 'should be at /outcome/indicators
navigator.MoveToFirstChild() 'should be at /outcome/indicators/indicator
navigator.MoveToFirstChild() 'should be at /outcome/indicators/indicator/p
'now what? I want to loop through the <p> elements and have some sort of do statement and write them to
'to the IndForm.Listbox1
IndForm.Show()
End Sub
真实文件中每个 ID 都有许多“p”元素。任何帮助(我相信有一种更简单的方法可以做到这一点。