使用 Nokogiri HTML Builder 创建具有多个根节点的片段 [英] Using Nokogiri HTML Builder to create fragment with multiple root nodes

查看:47
本文介绍了使用 Nokogiri HTML Builder 创建具有多个根节点的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我对 Nokogiri 有一个简单的问题.我想让 Nokogiri::HTML::Builder 制作以下形式的 HTML 片段:

#这里有些东西

<div>#这里还有一些其他的东西

尝试执行时:

@builder = Nokogiri::HTML::Builder.new(:encoding => 'UTF-8') do |doc|文档.div {doc.p第一次测试"}文档.div {doc.p第二次测试"}结尾@builder.to_html

我收到一个错误:Document has already a root node,我部分理解.我知道我没有将整个事情包装成标签(Nokogiri 期望这是因为 Nokogiri::HTML::Builder 继承自 Nokogiri::XML::Builder 并且 XML 文档必须有一个根节点).但我不是在构建 XML 文档.

我错过了什么吗?非常感谢任何形式的帮助.

解决方案

正如您所指出的,Builder 不允许您构建具有多个根节点的 HTML 文档.您需要使用 DocumentFragment

@doc = Nokogiri::HTML::DocumentFragment.parse ""Nokogiri::HTML::Builder.with(@doc) do |doc|文档.div {doc.p第一次测试"}文档.div {doc.p第二次测试"}结尾把@doc.to_html

Well I have a simple problem with Nokogiri. I want to make Nokogiri::HTML::Builder to make an HTML fragment of the following form:

<div>
#Some stuff in here
</div>
<div>
#Some other stuff in here
</div>

When trying to do:

@builder = Nokogiri::HTML::Builder.new(:encoding => 'UTF-8') do |doc|
    doc.div {
      doc.p "first test"
    }
    doc.div {
      doc.p "second test"
    }
  end
@builder.to_html

I get an error: Document has already a root node, which I partly understand. I know I am not wrapping the whole thing into tags (which Nokogiri expects as Nokogiri::HTML::Builder inherits from Nokogiri::XML::Builder and an XML document must have a root node). But I am not building an XML document.

Am I missing something? Any kind of help is much appreciated.

解决方案

As you noted, Builder will not allow you to build an HTML document with multiple root nodes. You'll need to use DocumentFragment

@doc = Nokogiri::HTML::DocumentFragment.parse ""

Nokogiri::HTML::Builder.with(@doc) do |doc|
    doc.div {
      doc.p "first test"
    }
    doc.div {
      doc.p "second test"
    }
end

puts @doc.to_html

这篇关于使用 Nokogiri HTML Builder 创建具有多个根节点的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆