使用 xpath 选择具有特定属性子节点的节点 [英] Select nodes with specific attribute children nodes using xpath

查看:52
本文介绍了使用 xpath 选择具有特定属性子节点的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

推荐答案

如果你需要做的就是获取玩家名称列表,其中他们组的 Sort 属性等于 "Attack",你可以这样做:

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

这篇关于使用 xpath 选择具有特定属性子节点的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆