From: Paul Battley Date: 2006-08-02T17:45:20+09:00 Subject: Re: REXML XPath: bug or misunderstanding? On 02/08/06, Robert Klemme wrote:> Eric Armstrong wrote:> > ...> > According to the XPath doc, the first argument> > is the "context" element.> >> > So what /should/ happen is that search> > for td elements occurs in the subtree> > rooted at the tbl element, using the> > //td path --which I take to mean "anywhere> > within the context".> >> > But what actually happens is that the> > search for td elements occurs in the> > entire document, so the code above returns> > the first table, regardless of where the> > matching data is found.>> That sounds like a bug. That's what I thought when I first encountered it, but after lookinginto it in more detail I concluded that it follows the specification.The receiving element does indeed provide context, but using //overrides it: // means the root node or any of its descendants. > > The workaround is to dispense with the> > outer loop. Once matching data is found> > and keep visiting parents until the> > table ancestor is found. (That patch> > simplifies the code, actually.)>> IMHO the proper solution is to craft a single XPath expression that will> cover your requirement, i.e. any "td" somewhere below a "table". In general, that is indeed likely to be the best solution. However,just to clear things up, here's how the original poster could havedone what he wanted: use "descendant::td". Here's an example: xml = %{ } doc = REXML::Document.new(xml) REXML::XPath.each(doc, '//b') do |b| REXML::XPath.each(b, 'descendant::d') do |d| puts(d.to_s) end end # => For comparison: REXML::XPath.each(doc, '//b') do |b| REXML::XPath.each(b, '//d') do |d| puts(d.to_s) end end # => # => Regards,Paul.