How to check if a particular node is present in XML in Ruby -
i want check if node present under specific node, can present in level. (it can deeper).
for xml:
<main> <sub> <inner> <first></first> <second></second> </inner> </sub> </main>
how check see whether sub
node has inner node first
or not, using nokogiri without using xpath '/sub/inner'
directly?
your xpath isn't correct unless know sub
node @ top level. think of xpath selectors paths in os. /sub
@ root of drive.
i'd recommend using css selectors clarity:
require 'nokogiri' doc = nokogiri::html(<<eot) <main> <sub> <inner> <first>first_text</first> <second></second> </inner> </sub> </main> eot doc.at('sub first').text # => "first_text"
'sub first'
means first
has exist somewhere under 'sub'
.
this might help:
require 'nokogiri' doc = nokogiri::html(<<eot) <main> <sub> <inner> <first>first_text</first> <second></second> </inner> </sub> </main> eot doc.at('/sub/first') # => nil doc.at('sub first') # => #<nokogiri::xml::element:0x3fd580c9e54c name="first" children=[#<nokogiri::xml::text:0x3fd580c9e2f4 "first_text">]> doc.at('//sub/*/first') # => #<nokogiri::xml::element:0x3fd580c9e54c name="first" children=[#<nokogiri::xml::text:0x3fd580c9e2f4 "first_text">]> doc.at('//sub//first') # => #<nokogiri::xml::element:0x3fd580c9e54c name="first" children=[#<nokogiri::xml::text:0x3fd580c9e2f4 "first_text">]> doc.at('sub first').text # => "first_text" doc.at('//sub/*/first').text # => "first_text" doc.at('//sub//first').text # => "first_text"
Comments
Post a Comment