Jim Horng
Jim Horng

Reputation: 1677

Ruby: How to find XML child element from specific element using xpath?

Given xml

<a>
    <b key=1>
        <c value=xxx />
    </b>
    <b key=2>
        <c value=yyy />
    </b>
</a>

Goal: Get each "b" first, then get the "c" under that "b", like result below. With XPath for searching child.

for <b key=1>
    <c value=xxx />
for <b key=2>
    <c value=xxx />

but below code

b_elements = XPath.match(xml, "//b[@key]")
b_elements.each do |b_element|
    puts b_element.elements["//c"]
end

will result in yeilding

for <b key=1>
    <c value=xxx />
    <c value=yyy />
for <b key=2>
    <c value=xxx />
    <c value=yyy />

instead of just getting the "c" under each "b"

I had tried below method but no luck, seems that if using Xpath, it will automatically search from root element

b.get_elements("//c")
XPath.first(b, "//c")

My workaround now is traverse child element 1 layer at a time and search for desired key, which seems quite stupid comparing to using XPath. Please advise, thanks : )

Reference: http://ruby-doc.org/stdlib-1.9.3/libdoc/rexml/rdoc/REXML/Element.html#method-i-each_element_with_attribute

Upvotes: 1

Views: 1494

Answers (1)

NIA
NIA

Reputation: 2543

Not sure here, but my assumption is that XPath looks at the first char, sees that it is a /, and thinks that the path is absolute (because the path starting with / is meant to be absolute).

Probably you can force the path to be relative by using a . before //, so the parser doesn't confuse // for /?

I mean, instead of "//c" use ".//c"? Hope this helps.

Upvotes: 1

Related Questions