English 中文(简体)
在规定的节点之后取消所有节点[复制]
原标题:Remove all nodes after a specified node [duplicate]

I m grabbing a div of text from a url and 我想去掉一个有backtotop的段落下的一切。 班级。 我在这里看到了一部关于 st流的反射法,它充满希望,但我可以指出,如何将它纳入到这样一页的@el中,只包含在四版的第一份<代码>p.backtotop之前的所有东西。

我的法典:

@doc = Nokogiri::HTML(open(url))
@el = @doc.css("div")[0]
end

背信弃义:

doc = Nokogiri::HTML(code)
stop_node = doc.css("p.backtotop")
doc.traverse do |node|
break if node == stop_node
# else, do whatever, e.g. `puts node.name`
end
问题回答
  1. Find the div you want.
  2. Find the stop item you want, and then find all the following siblings.
  3. Remove them.

例如:

<body>
  <div id="a">
    <h2>My Section</h2>
    <p class="backtotop">Back to Top</p>
    <p>More Content</p>
    <p>Even More Content</p>
  </div>
</body>
require  nokogiri 
doc = Nokogiri::HTML(my_html)
div = doc.at( #a )
div.at( .backtotop ).xpath( following-sibling::* ).remove
puts div
#=> <div id="a">
#=>     <h2>My Section</h2>
#=>     <p class="backtotop">Back to Top</p>
#=>     
#=>     
#=>   </div>

更复杂的例子是<代码>后至 2. 本项不得成为四分五裂的根源:

<body>
  <div id="b">
    <h2>Another Section</h2>
    <section>
      <p class="backtotop">Back to Top</p>
      <p>More Content</p>
     </section>
    <p>Even More Content</p>
  </div>
</body>
require  nokogiri 
doc = Nokogiri::HTML(my_html)
div = doc.at( #b )
n   = div.at( .backtotop )
until n==div
  n.xpath( following-sibling::* ).remove
  n = n.parent
end

puts div
#=> <div id="b">
#=>     <h2>Another Section</h2>
#=>     <section><p class="backtotop">Back to Top</p>
#=>       
#=>      </section>
#=>   </div>

如果您的超文本比上述内容更加复杂,请提供您希望得到的实际样本。 这是你今后提出的任何问题的良好建议。





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...