Nokogiri: Select content between element A and B

前端 未结 3 981
误落风尘
误落风尘 2020-12-15 01:40

What\'s the smartest way to have Nokogiri select all content between the start and the stop element (including start-/stop-element)?

Check example code below to unde

3条回答
  •  借酒劲吻你
    2020-12-15 02:39

    # monkeypatches for Nokogiri::NodeSet
    # note: versions of these functions will be in Nokogiri 1.3
    class Nokogiri::XML::NodeSet
      unless method_defined?(:index)
        def index(node)
          each_with_index { |member, j| return j if member == node }
        end
      end
    
      unless method_defined?(:slice)
        def slice(start, length)
          new_set = Nokogiri::XML::NodeSet.new(self.document)
          length.times { |offset| new_set << self[start + offset] }
          new_set
        end
      end
    end
    
    #
    #  solution #1: picking elements out of node children
    #  NOTE that this will also include whitespacy text nodes between the 

    elements. # possible_matches = parent.children start_index = possible_matches.index(@start_element) stop_index = possible_matches.index(@end_element) answer_1 = possible_matches.slice(start_index, stop_index - start_index + 1) # # solution #2: picking elements out of a NodeSet # this will only include elements, not text nodes. # possible_matches = value.xpath("//body/*") start_index = possible_matches.index(@start_element) stop_index = possible_matches.index(@end_element) answer_2 = possible_matches.slice(start_index, stop_index - start_index + 1)

提交回复
热议问题