0

我在从包含特定属性的父节点读取子节点时遇到小问题。

这是我的xml:

<Players>
  <Group Sort="Attack">
    <Player Name="John"/>
    <Player Name="John"/>
  </Group>
  <Group Sort="Defense">
    <Player Name="Thomas"/>
    <Player Name="Frank"/>
  </Group>
</Players>

这是我的代码:

Dim FullList As New XmlDocument
FullList.Load("FullList.xml")
Dim ReadPlayer as string = Nothing
Dim ReadList As XmlNodeList = FullList.SelectNodes("/Players/Group")

For Each ReadNode As XmlNode In ReadList
    If ReadNode IsNot Nothing Then
        Dim ReadNodeAttribute as XmlAttribute = ReadNode .Attributes("Sort")
        If ReadNodeAttribute IsNot Nothing Then
            If ReadNodeAttribute.Value = "Attack" then
                Dim answer As String = "YES"
                Dim NameList As XmlNodeList = FullList.SelectNodes("/Players/Group[@Sort = '" & ReadNodeAttribute.Value & "' ]/Player")
                For Each Name As XmlNode In NameList
                    If Name IsNot Nothing Then
                        Dim NameAttribute As XmlAttribute = Name.Attributes("Name")
                        If NameAttribute IsNot Nothing Then
                            MsgBox(NameAttribute.Value & answer)
                        End If
                    End If
                Next
            End If
        End If
    End If
Next

问题是我不明白NameAttribute.Value

我认为选择节点有问题,但我不确定具体在哪里。

4

2 回答 2

3

如果您需要做的只是获取Sort他们组的属性为 equals的玩家姓名列表"Attack",您可以执行以下操作:

Dim doc As New XmlDocument()
doc.Load("test.xml")
For Each ReadNode As XmlNode In doc.SelectNodes("/Players/Group[@Sort='Attack']/Player/@Name")
    MessageBox.Show(ReadNode.InnerText)
Next
于 2013-07-23T13:39:15.077 回答
1

如果你有兴趣使用XLINQ它,你可以使用(Imports System.Xml.XPath):

    Dim xDoc = <Players>
               <Group Sort="Attack">
                   <Player Name="John"/>
                   <Player Name="John"/>
               </Group>
               <Group Sort="Defense">
                   <Player Name="Thomas"/>
                   <Player Name="Frank"/>
               </Group>
           </Players>
Dim query = xDoc.XPathSelectElements("//Group[@Sort='Attack']/Player")

For Each ele In query
    MsgBox(ele.@Name)
Next ele
于 2013-07-23T13:48:52.280 回答