简体   繁体   English

将div添加到Nokogiri XML NodeSet

[英]Add div to Nokogiri XML NodeSet

I'm just trying to add a "dummy" div into the head of this HTML snippet, and I've tried 100 ways and nothing is working. 我只是想在此HTML代码段的开头添加“虚拟” div,并且尝试了100种方法,但没有任何效果。

This is what the head looks like when I pull it down: 这是当我将其拉下时的head外观:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Horraa</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</head>

I just want to put in this dummy div: 我只想输入这个虚拟div:

<div> id='todd' class='{{customer.name}} {{shop.domain}}'</div>

So the end result is this 所以最终结果是这样

<head>
<div> id='todd' class='{{customer.name}} {{shop.domain}}'</div>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Horraa</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</head>

This is my Nokogiri 这是我的Nokogiri

page = Nokogiri::HTML(todd)
head = page.css('head')

Head is now a Nokogiri::XML::NodeSet Head现在是Nokogiri::XML::NodeSet

This doesn't work 这不行

div = "<div> id='todd' class='{{customer.name}} {{shop.domain}}'</div>"
head.push(div)

Or this 或这个

div = "<div> id='todd' class='{{customer.name}} {{shop.domain}}'</div>"
update = Nokogiri::XML::Node.new('div', todd)
update['class'] = '{{customer.name}} {{shop.domain}}'
head.add_previous_sibling(update)
head << update

or this 或这个

head.add_next_sibling "<div> id='todd' class='{{customer.name}} {{shop.domain}}'</div>"

and I've tried 10 others, but this is getting long.. Where did I go astray? 并且我已经尝试了10个,但这已经变得很长了。

Try this 尝试这个

html_string = "<div id='todd' class='{{customer.name}} {{shop.domain}}'></div>"
page.at('head').add_child(html_string)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM