html - 如何在不创建不需要的自定义标签的情况下使用 Nokogiri::HTML.fragment
问题描述
我有支持 Nokogiri 的 HTML 碎片的 Ruby 代码。
当用户"<"
向应用程序输入文本时,Nokogiri::HTML.fragment
将其添加到自定义 HTML 标记。
如果用户输入类似
"One <two three"
该应用程序将显示它像
"one <two three></two>"
我正在使用Nokogiri::HTML.fragment(html, encoding = 'UTF-8')
.
有谁知道如何修理它?
解决方案
您不了解 HTML 与解析器的文本有何不同。Nokogiri 认为这one <two three
是 HTML 并尝试对其进行验证,看到<two three
并认为它是一个标记<two
后跟一个参数,但没有看到结束>
,因此它进行了一些修复以试图提供帮助。
require 'nokogiri'
doc = Nokogiri::HTML::DocumentFragment.parse('one <two three')
doc.to_html # => "one <two three></two>"
相反,就像您想创建一个包含 的页面一样one <two three
,您必须提供 HTML 编码文本:
doc = Nokogiri::HTML::DocumentFragment.parse('one <two three')
doc.to_html # => "one <two three"
您可以使用 HTML Entities gem 自动执行此操作:
require 'htmlentities'
coder = HTMLEntities.new
doc = Nokogiri::HTML::fragment(coder.encode('one <two three'))
doc.to_html # => "one <two three"
推荐阅读
- python - Python for loop zip 函数的输出字典比旧字典的输入键多
- node.js - Socket io 广播方法也从第二个动作向发送者广播
- python - Beaglebone Black 和 MCP230xx CircuitPython 库
- algorithm - 多边形中的点 3d(同一平面)算法
- javascript - 如何在 AngularJS 1.x 中使用 Jasmine 和 Karma 获取单选按钮的 ng-model 值
- powershell - 如何结合 Get-ChildItem 和 Get-FileHash 输出?电源外壳
- python - NumPy 中的链式比较?
- javascript - 如何检查嵌套 forLoop 中的所有元素是否为假并将答案返回/存储在变量中?反应 JS
- java - 无法在 Python 中发布文件 [使用 Java]
- oracle-apex - 使用动态 DATE 列进行透视