How to get text after or before certain tags using Nokogiri

雨燕双飞 提交于 2020-01-01 17:10:12

问题


I have an HTML document, something like this:

<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>

I want to extract:

# one
# two 
# three
# four
# first
# second
# third
# fourth
</root>

In other words, I want "all text after <template element="1"><title>test</title></template> and before the next tag that starts after that."

I can get all text between root using '//root/text()' but how do I get all text before and after certain tags?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4404746/how-to-get-text-after-or-before-certain-tags-using-nokogiri

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