How can I get the next sibling of an GPathResult? For example I have the following code:
def priorityIssue = xmlReport.'**'.find { Issue ->
Issue.Priority.text() == priority
}
How do I get priorityIssue's next sibling?
Thanks!
How can I get the next sibling of an GPathResult? For example I have the following code:
def priorityIssue = xmlReport.'**'.find { Issue ->
Issue.Priority.text() == priority
}
How do I get priorityIssue's next sibling?
Thanks!
More or less this is the way to go:
import groovy.util.XmlSlurper
def xml = new XmlSlurper().parseText('''
<issues>
<issue>
<id>1</id>
<priority>1</priority>
</issue>
<issue>
<id>2</id>
<priority>2</priority>
</issue>
</issues>
''')
def p = '1'
def priorityIssue = xml.'**'.find { issue ->
issue.priority.text() == p
}
def kids = priorityIssue.parent().children().list()
def idx = kids.indexOf(priorityIssue)
def sibling = kids[++idx]
assert sibling.id.text() == '2'
The solution with indexOf()
works only if you search for a node with unique text content. The problem is, that NodeChild
instances are always compared by text()
, see GPathResult#hashCode()
. I had to get to the actual nodes instead of their proxies NodeChild
.
xml = new groovy.util.XmlSlurper().parseText('''\
<issues>
<issue>
<first/>
<priority>1</priority>
</issue>
<issue>
<second/>
<priority>2</priority>
</issue>
<issue>
<third/>
<priority>1</priority>
</issue>
</issues>
''')
third = xml.'**'.find{it.name() == 'third'}
thirdIssue = third.parent()
issues = thirdIssue.parent().children()
println 'wrong: ' + issues.list().indexOf(thirdIssue)
println 'right: ' + issues.findIndexOf{it[0] == thirdIssue[0]}
Extra tip: You can also use Integer.toHexString(System.identityHashCode(issue))
to check, what instances are you dealing with.