如何初始化Nokogiri :: XML :: Element

时间:2019-06-26 14:59:50

标签: ruby nokogiri

我想使用以下方法初始化Nokogiri::XML::Element对象:

html = '<a href="https://example.com">Link</a>'
Nokogiri::XML::Element.new(html)

但是目前我必须这样做:

Nokogiri::HTML::DocumentFragment.parse(html).children.last

有更好的方法吗?

2 个答案:

答案 0 :(得分:4)

Nokogiri提供了make方法(Nokogiri::make)作为创建DocumentFragment的便捷方法,其代码与您现在正在执行的操作几乎相同:

def make input = nil, opts = {}, &blk
  if input
    Nokogiri::HTML.fragment(input).children.first
  else
    Nokogiri(&blk)
  end
end

示例:

html = '<a href="https://example.com">Link</a>'
require 'nokogiri'
Nokogiri.make(html)
#=> #<Nokogiri::XML::Element:0x2afe5af3a04c name="a" attributes=
#    [#<Nokogiri::XML::Attr:0x2afe5ac33efc name="href" value="https://example.com">] 
#     children=[#<Nokogiri::XML::Text:0x2afe5ac32408 "Link">]>

其他选项包括

Nokogiri(html).first_element_child
Nokogiri.parse(html).first_element_child

答案 1 :(得分:0)

您正在寻找Nokogiri::HTML.fragment

html = '<a href="https://example.com">Link</a>'
Nokogiri::HTML.fragment html
#=> #(DocumentFragment:0x2b296b79c0c4 { name = "#document-fragment", children = [ #(Element:0x2b296919d724 { name = "a", attributes = [ #(Attr:0x2b296919d6fc { name = "href", value = "https://example.com" })], children = [ #(Text "Link")] })] })
asd.children.last
#=> #(Element:0x2b296b7cbe50 { name = "a", attributes = [ #(Attr:0x2b296b7cbe28 { name = "href", value = "https://example.com" })], children = [ #(Text "Link")] })