【问题标题】:How to use [% special characters in Nokogiri如何在 Nokogiri 中使用 [% 特殊字符
【发布时间】:2019-10-30 04:19:28
【问题描述】:

我在 Rails 中使用 Nokogiri 来解析我的 HTML 并将自闭合标签转换为常规标签。这很好用,但它也转换了我们的模板标签 [%%],例如:

html = "<a href='[% hello %]'>Hello from [% Us %]</a>"
Nokogiri::HTML::DocumentFragment.parse(html).to_html

将转换为:

<a href='%5B%%20hello%20%%5D'>Hello from [% Us %]</a>

转换后不使用gsub如何避免?

这没有帮助:

html = "<a href='[% hello %]'>Hello from [% Us %]</a>"
doc = Nokogiri::HTML::Document.new
doc.encoding = 'UTF-8'
doc.fragment(html).to_html
#=> "<a href=\"%5B%%20hello%20%%5D\">Hello from [% Us %]</a>" 

【问题讨论】:

  • @anothermh 请参阅上面的更新。推荐的解决方案似乎没有帮助。也许是 .to_html ?如果是这样,正确的方法是什么?
  • 赞成确定问题范围并提供可以轻松运行的测试代码????。您能否用预期的输出更新问题?
  • @Ben Try doc.fragment(html).to_xml => "&lt;a href=\"[% hello %]\"&gt;Hello from [% Us %]&lt;/a&gt;"。应该可以工作,因为它是 XML,而且 XML 不一定知道 HTML 实体。

标签: ruby-on-rails ruby nokogiri


【解决方案1】:

@anothermh 实际上回答了我的问题(请参阅我的问题下方的 cmets)。我最终采纳了他的建议 (to_xml)

但是,我需要更多地解析我的代码,而不是我决定不提的。我需要能够保留标签中的特殊字符,但也需要将自闭合标签转换为常规标签。

我的解决方案是使用 XHTML 格式,如下所述:https://www.rubydoc.info/github/sparklemotion/nokogiri/Nokogiri/XML/Node/SaveOptions#FORMAT-constant

html = "... my html ..."    
doc = Nokogiri::HTML::Document.new
doc.encoding = 'UTF-8'
final = doc.parse(html).to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::DEFAULT_XHTML)

【讨论】:

    猜你喜欢
    • 2017-05-10
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 2016-10-01
    相关资源
    最近更新 更多