From: djberg96@... (Daniel Berger) Date: 2004-09-04T00:30:17+09:00 Subject: Re: rexml help James Britt wrote in message news:<41380BDD.4040905@neurogami.com>... > 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 Thank you James. I have a followup issue. There are some attributes that are optional, such as "interval". If I try to use XPath in this fashion.. interval = parent.elements.to_a( "interval" )[0].text ...and the "interval" node doesn't exist, it's going to raise a NoMethodError. I *could* just rescue and ignore that error, but that doesn't seem very clean. Is there a better way? Or do I simply tell people they must include the optional tags, even if they're empty? Dan