【发布时间】:2014-10-07 17:33:14
【问题描述】:
如果您查看后面部分的输出,ruby 正在删除所有 html 实体。如何在不丢失 HTML 实体的情况下使用 nokogiri 解析 XML?
--- BEFORE ---
<blog:entryFull>
<p><iframe src="http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F39858946&amp;show_artwork=true" width="100%" height="166" frameborder="no" scrolling="no"></iframe></p></blog:entryFull>
--- AFTER ---
<blog:entryFull>
piframe src="http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F39858946amp;show_artwork=true" width="100%" height="166" frameborder="no" scrolling="no"/iframe/p</blog:entryFull>
</blog:example>
代码如下:
f = File.open(item)
contents = ""
f.each {|line|
contents << line
}
puts "--- BEFORE ---"
puts contents
puts "--- AFTER ---"
doc = Nokogiri::XML::DocumentFragment.parse(contents)
puts doc
f.close
【问题讨论】:
-
puts doc将尝试对文档进行字符串化,这不是您想要的。您必须告诉 Nokogiri 您希望如何查看文档/节点,如 HTML、XHTML 或 XML。更多信息在the Nokogiri::XML::Node documentation。 -
我有一个相关的问题:
puts Nokogiri::XML::DocumentFragment.parse( "<pre>&lt;div>foo&lt;/div></pre>" )给了<pre>&lt;div&gt;foo&lt;/div&gt;</pre>但puts Nokogiri::XML::DocumentFragment.parse( "&nbsp;<pre>&lt;div>foo&lt;/div></pre>" )给了"<pre>div&gt;foo/div&gt;</pre>"