vb.net 使用 xpath 选择具有特定属性子节点的节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17808399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select nodes with specific attribute children nodes using xpath
提问by Chelovek
I am having small issue reading children nodes from parent node containing specific attribute.
我在从包含特定属性的父节点读取子节点时遇到了小问题。
Here is my xml:
这是我的 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
问题是我不明白 NameAttribute.Value
I think that there is problem with selecting nodes, but I am not sure where exactly.
我认为选择节点有问题,但我不确定具体在哪里。
回答by Steven Doggart
If all you need to do is get the list of player names where the Sortproperty of their group equals "Attack", you could just do something like this:
如果您需要做的就是获取玩家名称列表,其中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
回答by Cylian
If you're interested to use XLINQfor this, you could use(Imports System.Xml.XPath):
如果您对此感兴趣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

