Tôi muốn lấy html bên trong không thoát khỏi một Node Nokogiri. Có ai biết cách để làm điều này không?Làm thế nào để có được inner_html của Nokogiri NodeSet ruby không bị thoát?
7
A
Trả lời
4
Bất cứ điều gì không phải là okey?
nodeset.inner_html
0
Phiên bản cũ của libxml2 có thể khiến Nokogiri trả về một số ký tự thoát. Tôi đã gặp vấn đề này gần đây.
2
Đá quý loofah đã giúp tôi rất nhiều ở đây.
1
Bọc nút của bạn trong CDATA:
def wrap_in_cdata(node)
# Using Nokogiri::XML::Node#content instead of #inner_html (which
# escapes HTML entities) so nested nodes will not work
node.inner_html = node.document.create_cdata(node.content)
node
end
Nokogiri::XML::Node#inner_html
thoát thực thể HTML ngoại trừ trong các phần CDATA.
fragment = Nokogiri::HTML.fragment "<div>Here is an unescaped string: <span>Turn left > right > straight & reach your destination.</span></div>"
puts fragment.inner_html
# <div>Here is an unescaped string: <span>Turn left > right > straight & reach your destination.</span></div>
fragment.xpath(".//span").each {|node| node.inner_html = node.document.create_cdata(node.content) }
fragment.inner_html
# <div>Here is an unescaped string: <span>Turn left > right > straight & reach your destination.</span>\n</div>