Chelovek
Chelovek

Reputation: 159

Select nodes with specific attribute children nodes using xpath

I am having small issue reading children nodes from parent node containing specific attribute.

Here is my xml:

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

Here is my code:

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

The problem is I don't get NameAttribute.Value

I think that there is problem with selecting nodes, but I am not sure where exactly.

Upvotes: 0

Views: 8300

Answers (2)

Cylian
Cylian

Reputation: 11182

If you're interested to use XLINQ for this, you could use(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

Upvotes: 1

Steven Doggart
Steven Doggart

Reputation: 43743

If all you need to do is get the list of player names where the Sort property of their group equals "Attack", you could just do something like this:

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

Upvotes: 3

Related Questions