rexml - 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: each "b" first, "c" under "b", result below. xpath searching child.
for <b key=1> <c value=xxx /> <b key=2> <c value=xxx /> but below code
b_elements = xpath.match(xml, "//b[@key]") b_elements.each |b_element| puts b_element.elements["//c"] end will result in yeilding
for <b key=1> <c value=xxx /> <c value=yyy /> <b key=2> <c value=xxx /> <c value=yyy /> instead of getting "c" under each "b"
i had tried below method no luck, seems if using xpath, automatically search root element
b.get_elements("//c") xpath.first(b, "//c") my workaround traverse child element 1 layer @ time , search desired key, seems quite stupid comparing using xpath. please advise, : )
not sure here, assumption xpath looks @ first char, sees /, , thinks path absolute (because path starting / meant absolute).
probably can force path relative using . before //, parser doesn't confuse // /?
i mean, instead of "//c" use ".//c"? hope helps.
Comments
Post a Comment