How to get text after or before certain tags using Nokogiri

青春壹個敷衍的年華 提交于 2019-12-04 18:06:16

This seems to work:

require 'nokogiri'

xml = '<root>
    <template>title</template>
    <h level="3" i="3">Something</h>
    <template element="1">
        <title>test</title>
    </template>
    # one
    # two
    # three
    # four
    <h level="4" i="5">something1</h>
    some random test
    <template element="1">
        <title>test</title>
    </template>
    # first
    # second
    # third
    # fourth
    <template element="2">
        <title>testing</title>
    </template>
</root>
'

doc = Nokogiri::XML(xml)
text = (doc / 'template[@element="1"]').map{ |n| n.next_sibling.text.strip.gsub(/\n  +/, "\n") }
puts text
# >> # one
# >> # two
# >> # three
# >> # four
# >> # first
# >> # second
# >> # third
# >> # fourth

I'm pretty sure krusty.ar is right that there's not a built-in method for achieving this. You can just remove all the tags inside the root tag one by one if you'd like. It's a hack, but it works:

doc = Nokogiri::HTML(open(url)) # or Nokogiri::HTML.parse(File.open(file_path))
doc.xpath('//template').remove
doc.xpath('//h').remove
doc

That gives the result you're looking for with the HTML you posted.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!