Hello!
I try to understand REXML using the tutorial in
http://www.germane-software.com/software/rexml/docs/tutorial.html
However, I have problems applying the path expressions to my
application.
Consider for example the following program, and in particular the last
line:
#!/usr/bin/ruby
require “rexml/document”
require ‘pp’
source=<<ENDXML
ns:toplevel
<ns:request requestID=“1”>
<ns:application aid=“demo-a”>
</ns:application>
</ns:request>
<ns:request requestID=“2”>
<ns:application aid=“demo-b”>
</ns:application>
</ns:request>
</ns:toplevel>
ENDXML
doc=REXML::Document.new source
doc.elements.each(“ns:toplevel/ns:request”) { |element| puts
element.attributes[“requestID”] }
root=doc.root
pp root.elements[“ns:toplevel/ns:request[@requestID=‘2’]”]
The program outputs
1
2
nil
that is, it finds the two elements “request” and correctly outputs their
attribute
requestID, but when I try to locate request number two with the path
expression
ns:toplevel/ns:request[@requestID=‘2’]
it is not found. What am I doing wrong here?
Ronald
On 7/12/07, Ronald F. [email protected] wrote:
<ns:application aid="demo-b">
The program outputs
ns:toplevel/ns:request[@requestID=‘2’]
it is not found. What am I doing wrong here?
Your root variable represents your ns:toplevel so, either of these
would return an object instead of nil …
pp root.elements[“ns:request[@requestID=‘2’]”]
pp doc.elements[“ns:toplevel/ns:request[@requestID=‘2’]”]
Todd
On 7/12/07, Ronald F. [email protected] wrote:
Hello!
I try to understand REXML using the tutorial in
Hi,
You seem comfortable with XPath, so let me strongly encourage the
methods defined in the REXML::XPath class instead of the []-based
methods.
http://www.germane-software.com/software/XML/rexml/doc/classes/REXML/XPath.html
$ cat rbtalk.rb
#!/usr/bin/env ruby
require “rexml/document”
source=<<ENDXML
ns:toplevel
<ns:request requestID=“1”>
<ns:application aid=“demo-a”>
</ns:application>
</ns:request>
<ns:request requestID=“2”>
<ns:application aid=“demo-b”>
</ns:application>
</ns:request>
</ns:toplevel>
ENDXML
doc = REXML::Document.new source
REXML::XPath.each(doc, “/ns:toplevel/ns:request”) {|element|
puts element.attributes[“requestID”]
}
p REXML::XPath.match(doc, “/ns:toplevel/ns:request[@requestID=‘2’]”)
$ ruby ./rbtalk.rb
1
2
[<ns:request requestID=‘2’> … </>]
HTH,
Keith
You seem comfortable with XPath, so let me strongly encourage the
methods defined in the REXML::XPath class instead of the []-based
methods.
REXML::XPath.each(doc, “/ns:toplevel/ns:request”) {|element|
puts element.attributes[“requestID”]
}
p REXML::XPath.match(doc, “/ns:toplevel/ns:request[@requestID=‘2’]”)
Thanks a lot for the suggestion!
(And also thanks to Todd B. for pointing out my error).
Ronald