使用xpath选择具有特定属性子节点的节点

时间:2013-07-23 11:05:34

标签: xml vb.net xpath

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

这是我的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

我认为选择节点存在问题,但我不确定究竟在哪里。

2 个答案:

答案 0 :(得分:2)

如果您需要做的只是获取其组Sort属性等于"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

答案 1 :(得分: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