使用 Nokogiri 禁用 XML 中的 HTML 转义

boo*_*sey 2 ruby sinatra nokogiri

我正在尝试从 Google Directions API 解析 XML 文档。

这是我到目前为止所得到的:

x = Nokogiri::XML(GoogleDirections.new("48170", "48104").xml)
x.xpath("//DirectionsResponse//route//leg//step").each do |q|
  q.xpath("html_instructions").each do |h|
    puts h.inner_html
  end
end
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

Head <b>south</b> on <b>Hidden Pond Dr</b> toward <b>Ironwood Ct</b>
Turn <b>right</b> onto <b>N Territorial Rd</b>
Turn <b>left</b> onto <b>Gotfredson Rd</b>
...
Run Code Online (Sandbox Code Playgroud)

我希望输出是:

Turn <b>right</b> onto <b>N Territorial Rd</b>
Run Code Online (Sandbox Code Playgroud)

问题似乎是 Nokogiri 在 xml 中转义了 html

我信任谷歌,但我认为进一步清理它也很好:

Turn right onto N Territorial Rd
Run Code Online (Sandbox Code Playgroud)

但如果没有原始 xml,我就不能(也许使用清理)。有想法吗?

the*_*Man 5

因为我没有安装 Google Directions API,所以无法访问 XML,但我强烈怀疑问题是由于告诉 Nokogiri 您正在处理 XML 而导致的。结果,它将返回 HTML 编码,就像 XML 中应有的那样。

您可以使用以下命令对 HTML 进行转义:

CGI::unescape_html('Head &lt;b&gt;south&lt;/b&gt; on &lt;b&gt;Hidden Pond Dr&lt;/b&gt; toward &lt;b&gt;Ironwood Ct&lt;/b&gt;')
=> "Head <b>south</b> on <b>Hidden Pond Dr</b> toward <b>Ironwood Ct</b>\n"
Run Code Online (Sandbox Code Playgroud)

unescape_html是以下的别名unescapeHTML

对已进行 HTML 转义的字符串进行转义
  CGI::unescapeHTML("用法:foo "bar" <baz>")
     # => "用法: foo \"bar\" "

我必须再考虑一下这个问题。这是我遇到过的事情,但它是我在匆忙的工作中逃脱的事情之一。修复方法很简单:您使用了错误的方法来检索内容。代替:

puts h.inner_html
Run Code Online (Sandbox Code Playgroud)

使用:

puts h.text
Run Code Online (Sandbox Code Playgroud)

我用以下方法证明了这一点:

require 'httpclient'
require 'nokogiri'

# This URL comes from: https://developers.google.com/maps/documentation/directions/#XML
url = 'http://maps.googleapis.com/maps/api/directions/xml?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'
clnt = HTTPClient.new

doc = Nokogiri::XML(clnt.get_content(url))
doc.search('html_instructions').each do |html|
  puts html.text
end
Run Code Online (Sandbox Code Playgroud)

哪个输出:

Head <b>south</b> on <b>S Federal St</b> toward <b>W Van Buren St</b>
Turn <b>right</b> onto <b>W Congress Pkwy</b>
Continue onto <b>I-290 W</b>
[...]
Run Code Online (Sandbox Code Playgroud)

不同的是,inner_html是直接读取节点的内容,不进行解码。text为你解码。textto_str并且在 Nokogiri::XML::Node 内部inner_text被别名content为我们的解析乐趣。