From: William James Date: 2006-02-23T13:08:32+09:00 Subject: Re: Xpath to attributes listrecv@gmail.com wrote: > Is there anyway to do generic xpath's, for both elements and attributes > (ie //customer/phone/@type --> "home")? REXML can do xpath to fetch > elements (rexml_element.text('//customer/phone')) but can't seem to use > xpath to find attributes. class Array; alias atr first; alias txt last end class String def xtag(s) scan( %r! < #{s} (?: \s+ ( [^>]* ) )? / > | < #{s} (?: \s+ ( [^>]* ) )? > ( .*? ) !mx ). map{ |unpaired, attr, data| h = { } attr = ( unpaired || attr ) if attr attr.scan( %r! ( \S+ ) = ( ["'] ) ( .*? ) \2 !x ){ |k,q,v| h[k] = v } end [ h, data ] } end def xpath(s) s.scan(%r! [^/"]+ (?: "[^"]*" )? !x).inject([[nil,self]]){|ary,str| if "@" == str[0,1] str =~ /@(.*?)="(.*)"/ ary.select{|a,t| a[$1] == $2 } else return [] if [] == ary ary[0].txt.xtag(str) end } end end p DATA.read.xpath('customer/@loc="south"/phone/@type="mobi"') __END__ 0115 07807 0319 09802