I have an Nokogiri::XML::Element
in which looks like this:
我有一个Nokogiri::XML::元素,它看起来像这样:
<div class="berg">This is some text!</div>
What I want to do is just extract the text from the div (which is the Nokogiri Element) and then wrap the text with a new tag so it looks like this:
我要做的就是从div(即Nokogiri元素)中提取文本,然后用一个新的标签将文本包装起来,就像这样:
<div class="berg"><span>This is some text!</span></div>
The Nokogiri .wrap
functions seems to wrap tags, not their text contents with a new tag, I was wondering how you wrap the inter tag contents. Cheers.
包装函数似乎是包装标签,而不是用新的标签来包装它们的文本内容,我想知道如何包装标签内容。欢呼。
Edit: Took the answer below and did it very simply like this in one line:
编辑:把下面的答案写在一行中,非常简单:
tag.inner_html = "<span>#{tag.inner_html}</span>"
2 个解决方案
#1
4
You can set the inner_html
of the div element. Here's a working example:
可以设置div元素的inner_html。这里有一个工作示例:
html = '<div class="berg">This is some text!</div>'
doc = Nokogiri::HTML.fragment(html)
berg = doc.at('div.berg') # Or xpath, or whatever method you choose
# Wrap the text in <span>
berg.inner_html = "<span>#{berg.text}</span>"
puts doc #=> <div class="berg"><span>This is some text!</span></div>
The important part is the use of inner_html
, adding in the <span>
element and putting the existing text element inside it.
重要的部分是使用inner_html,添加元素并将现有的文本元素放入其中。
#2
3
You would do:
你会做的事:
doc.search('div.berg text()').wrap('<span>')
#1
4
You can set the inner_html
of the div element. Here's a working example:
可以设置div元素的inner_html。这里有一个工作示例:
html = '<div class="berg">This is some text!</div>'
doc = Nokogiri::HTML.fragment(html)
berg = doc.at('div.berg') # Or xpath, or whatever method you choose
# Wrap the text in <span>
berg.inner_html = "<span>#{berg.text}</span>"
puts doc #=> <div class="berg"><span>This is some text!</span></div>
The important part is the use of inner_html
, adding in the <span>
element and putting the existing text element inside it.
重要的部分是使用inner_html,添加元素并将现有的文本元素放入其中。
#2
3
You would do:
你会做的事:
doc.search('div.berg text()').wrap('<span>')