我有一個HTML字符串(例如<div class="input">hello</div>
),我想僅在字符串中的HTML標記爲label
(例如<label>Hi</label>
)時添加節點。使用Nokogiri添加節點
doc = Nokogiri::XML(html)
doc.children.each do |node|
if node.name == 'label'
# this code gets called
span = Nokogiri::XML::Node.new "span", node
span.content = "hello"
puts span.parent
# nil
span.parent = node
# throws error "node can only have one parent"
end
end
doc.to_html # Does not contain the span.
我不能爲我的生活了解我做錯了,任何幫助將大大讚賞。
編輯:這解決了我的問題,感謝您的答案!
# notice DocumentFragment rather than XML
doc = Nokogiri::HTML::DocumentFragment.parse(html_tag)
doc.children.each do |node|
if node.name == 'label'
span = Nokogiri::XML::Node.new "span", doc
node.add_child(span)
end
end
你想在哪裏顯示新的跨度? – 2014-09-02 12:02:49
你需要展示你的輸出/結果HTML應該是什麼樣子的例子。 – 2014-09-02 18:07:03