From: James Britt Date: 2004-09-03T15:15:07+09:00 Subject: Re: rexml help Daniel Berger wrote: > Hi all, > > > Given a name, I want to be able to grab the login and password. Or, > given both a name and a login, I want to be able to find the password. > In the event I am only given a name, and there is more than one entry > with that name, I want the first entry (from a top down perspective). > > What is the shortest route to accomplish this with rexml? I've been > futzing around with each, each_element, root, get_text - but I'm just > not quite getting the hang of it. > Play with this:: #------------------------------------------------------------ class REXML::Document def login_details( name ) ary = self.elements.to_a( "//name[text()='#{name}']" ) parent = ary[0].parent login = parent.elements.to_a( "login" )[0].text pwd = parent.elements.to_a( "password" )[0].text [login, pwd ] end end doc = REXML::Document.new( xml ) puts( doc.login_details( 'bar' ).inspect ) puts( doc.login_details( 'foo' ).inspect ) #------------------------------------------------------------ REXML + XPath is your friend. Basically, use XPath to select the node(s) you want. Then get the parent node. Then use XPath again to get additional child nodes from that (parent) node. James