Friday, December 11, 2009

Which Child Am I?

I don't know if this is worth blogging home about, but I've needed this solution a couple times, and I found myself referencing this blog entry draft, so I'll put it out there and maybe someone else will find it useful. The problem is I have an xml node, and I want to know the order it is (as an index integer) in relation to its siblings. You may have to modify this of course, if the children you are comparing are deeper down than 1.

def CAR_RECORDS = '''
  <car name='HSV Maloo' make='Holden' year='2006'>
    <record type='speed'>Production Pickup Truck with speed of 271kph</record>
  <car name='P50' make='Peel' year='1962'>
    <country>Isle of Man</country>
    <record type='size'>Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record>
  <car name='Royale' make='Bugatti' year='1931'>
    <record type='price'>Most Valuable Car at $15 million</record>

def records = new XmlSlurper().parseText(CAR_RECORDS)
def record =[2].country

int index = 0
Boolean found = false
record.parent().parent().children().each {
  if (it == record.parent()) {
    found = true
  } else if (!found) {
assert index == 3
return index